Before going in-depth, let me tell you all that - Yes, I've gone through all possible solutions provided on Stack-Overflow.
Problem Statement : I'm not able to read 'CarrierName' of my available SIM using iPhone
What did I tried : I've tried two different solutions, but I'm unable to read CarrierName.
Solution 1 : When I tried this solution I've received only "Carrier" as output, instead of CarrierName.
Solution 1 :
//--------------- CodeBase : Solution1 -----------------
let networkInfo = CTTelephonyNetworkInfo()
let carrier = networkInfo.serviceSubscriberCellularProviders?.first?.value
if let carrierName = carrier?.carrierName {
cell.textLabel?.text = carrierName
}
else{
cell.textLabel?.text = "No Data"
}
//-------------------------------------------------------
Output : Carrier
Solution 2 : When I tried this solution I've received "iPhone X" as output, instead of CarrierName.
Solution 2 :
//--------------- CodeBase : Solution2 -----------------
let networkInfo = CTTelephonyNetworkInfo()
let carrier = networkInfo.serviceSubscriberCellularProviders?.first?.value
if var carrierName = carrier?.carrierName {
if carrierName.contains("Carrier"){
carrierName = self.getCarrierName() ?? "No Data"
}
else{
cell.textLabel?.text = carrierName
}
}
else{
cell.textLabel?.text = "No Data"
}
//-------------------------------------------------------
Func : getCarrierName()
//--------------- CodeBase : Part of Solution2 -----------------
func getCarrierName() -> String? {
var carrierName: String?
let typeName: (Any) -> String = { String(describing: type(of: $0)) }
let statusBar = UIApplication.shared.value(forKey: "_statusBar") as! UIView
for statusBarForegroundView in statusBar.subviews {
if typeName(statusBarForegroundView) == "UIStatusBarForegroundView" {
for statusBarItem in statusBarForegroundView.subviews {
if typeName(statusBarItem) == "UIStatusBarServiceItemView" {
carrierName = (statusBarItem.value(forKey: "_serviceString") as! String)
}
}
}
}
return carrierName
}
//-------------------------------------------------------
Output : iPhone X i.e. It returns ModelName instead of CarrierName
Can someone, please help me to get - CarrierName.
In my case (Xcode 11.4, Swift 5.2, iPhone 8, iOS 13.3.1), I can get the proper carrier name.
Code snippet:
import CoreTelephony
if #available(iOS 12.0, *) {
if let providers = CTTelephonyNetworkInfo().serviceSubscriberCellularProviders {
providers.forEach { (key, value) in
print("key: \(key), carrier: \(value.carrierName ?? "nil")")
}
}
} else {
let provider = CTTelephonyNetworkInfo().subscriberCellularProvider
print("carrier: \(provider?.carrierName ?? "nil")")
}
The result in console is:
key: 0000000100000001, carrier: 中国电信
Related
We are using Introductory Prices on our app. And we have an issue only reproducible on one of our two QA devices which is an iPhone 6S (11.4.1) on the French App Store. The other is an iPhone 7 (12.0 with French App Store) and the app is not crashing.
We are using this extension based on the SKProduct extension provided by SwiftyStoreKit :
#available(iOS 11.2, *)
public extension SKProductDiscount {
public var localizedPrice: String? {
return priceFormatter(locale: priceLocale).string(from: price)
}
private func priceFormatter(locale: Locale) -> NumberFormatter {
let formatter = NumberFormatter()
formatter.locale = locale
formatter.numberStyle = .currency
return formatter
}
}
Used like this :
func updateWith(storeProducts: Set<SKProduct>) {
guard
let selfStoreInfo = storeProducts.filter({ $0.productIdentifier == self.id }).first else {
Logger.warn(message: "Subscription \(self.id) not found on store", .inAppPurchase)
return
}
if #available(iOS 11.2, *) {
if let promo = selfStoreInfo.introductoryPrice {
promotionId = selfStoreInfo.productIdentifier
price = promo.localizedPrice
originalPrice = selfStoreInfo.localizedPrice
} else {
price = selfStoreInfo.localizedPrice
}
} else {
price = selfStoreInfo.localizedPrice
}
}
When debugging we found that priceLocale is responsible for throwing the EXC_BREAKPOINT.
EDIT Could be linked to this : https://bugs.swift.org/browse/SR-7922?attachmentOrder=desc but it's strange that it would work on our iPhone 7 and not on the iPhone 6s
Try this:
DispatchQueue.global(qos: .default).async {
while true {
if !SKProduct().productIdentifier.isEmpty {
if let productPriceString: String = SC.storeProduct.localizedPrice {
DispatchQueue.main.async {
print(productPriceString)
}
}
break
}
// Some wait process like using "semaphore"
}
Replace SKProduct() with your product.
In my case, this occurs when the function accessed before the product initialized.
Is it possible to access the list of providers on the phone?
I already found a home provider. But it's not clear how to look at other providers.
struct InfoProvider {
let networkOperator: String
let country: String?
let mobileCountryCode: String?
let mobileNetworkCode: String?
}
func getHomeProvider() -> InfoProvider? {
var homeProvider: InfoProvider? = nil
let networkInfo = CTTelephonyNetworkInfo()
if let carrier = networkInfo.subscriberCellularProvider {
if let carrierName = carrier.carrierName {
homeProvider = InfoProvider(networkOperator: carrierName,
country: carrier.isoCountryCode,
mobileCountryCode: carrier.mobileCountryCode,
mobileNetworkCode: carrier.mobileNetworkCode)
}
}
return homeProvider
}
func getProviders() -> [InfoProvider] {
var providers = [InfoProvider]()
// home provider record
if let homeProvider = self.getHomeProvider() {
providers.append(homeProvider)
}
/*
recording of other providers
*/
return providers
}
I want to check if the wifi is off then show alert to the user to check his/her connectivity.
I find code like this but it checks if there is an internet connection, not checking if the wifi is on or off:
func isConnectionAvailble()->Bool{
var rechability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "www.apple.com").takeRetainedValue()
var flags : SCNetworkReachabilityFlags = 0
if SCNetworkReachabilityGetFlags(rechability, &flags) == 0
{
return false
}
let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection)
}
You can't.
With Apple's reachability class, you can distinguish three things according to the NetworkStatus struct:
typedef enum : NSInteger {
NotReachable = 0, // 1
ReachableViaWiFi, // 2
ReachableViaWWAN // 3
} NetworkStatus;
You have neither WiFi nor mobile data connection.
You have a WiFi connection, but you may or may not have a mobile data connection.
You have a mobile data connection, but no WiFi connection.
You can't check whether WiFi is turned off, or whether WiFi is turned on but there is no WiFi network nearby, or whether Airplane mode has been turned on.
For mobile data, you can use the telephony class to find whether your device is capable of mobile data connections (iPhone and not iPad, and SIM card plugged in), and you can detect whether mobile data is disabled in the preferences of your application.
Found the following, which was really helpful for me (found on the Apple Developer Forums). The below code works with Swift 4.
func fetchSSIDInfo() -> String {
var currentSSID = ""
if let interfaces:CFArray = CNCopySupportedInterfaces() {
for i in 0..<CFArrayGetCount(interfaces){
let interfaceName: UnsafeRawPointer = CFArrayGetValueAtIndex(interfaces, i)
let rec = unsafeBitCast(interfaceName, to: AnyObject.self)
let unsafeInterfaceData = CNCopyCurrentNetworkInfo("\(rec)" as CFString)
if unsafeInterfaceData != nil {
let interfaceData = unsafeInterfaceData! as Dictionary!
for dictData in interfaceData! {
if dictData.key as! String == "SSID" {
currentSSID = dictData.value as! String
}
}
}
}
}
return currentSSID
}
You can then check if a device is connected to Wi-Fi by the following:
if fetchSSIDInfo() != nil {
/* Wi-Fi is Connected */
}
Not perfect, but if the device is not connected to a Wi-Fi Network, you could then ask the user to connect to a Wi-Fi Network:
let wifiNotifcation = UIAlertController(title: "Please Connect to Wi-Fi", message: "Please connect to your standard Wi-Fi Network", preferredStyle: .alert)
wifiNotifcation.addAction(UIAlertAction(title: "Open Wi-Fi", style: .default, handler: { (nil) in
let url = URL(string: "App-Prefs:root=WIFI")
if UIApplication.shared.canOpenURL(url!){
UIApplication.shared.openURL(url!)
self.navigationController?.popViewController(animated: false)
}
}))
self.present(wifiNotifcation, animated: true, completion: nil)
Tested with swift 4 and swift 5
let nwPathMonitor = NWPathMonitor()
nwPathMonitor.pathUpdateHandler = { path in
if path.usesInterfaceType(.wifi) {
print("Path is Wi-Fi")
} else if path.usesInterfaceType(.cellular) {
print("Path is Cellular")
} else if path.usesInterfaceType(.wiredEthernet) {
print("Path is Wired Ethernet")
} else if path.usesInterfaceType(.loopback) {
print("Path is Loopback")
} else if path.usesInterfaceType(.other) {
print("Path is other")
}
}
nwPathMonitor.start(queue: .main)
As already #abba_de_bo mentioned: you could fetch the current SSID and check if it's set or nil.
This is the answer Apple's Eskimo gave to this question:
The trick with using CF-based APIs from Swift is to get the data into ‘Swift space’ as quickly as possible.
func currentSSIDs() -> [String] {
guard let interfaceNames = CNCopySupportedInterfaces() as? [String] else {
return []
}
return interfaceNames.flatMap { name in
guard let info = CNCopyCurrentNetworkInfo(name as CFString) as? [String:AnyObject] else {
return nil
}
guard let ssid = info[kCNNetworkInfoKeySSID as String] as? String else {
return nil
}
return ssid
}
}
Note that this returns an array of names; how you handle the non-standard cases (no elements, more than one element) is up to you.
Make sure you import SystemConfiguration.CaptiveNetwork. Otherwise the build will fail with on of those error messages:
Use of unresolved identifier 'CNCopySupportedInterfaces'
Use of unresolved identifier 'CNCopyCurrentNetworkInfo'
Use of unresolved identifier 'kCNNetworkInfoKeySSID'
You can take a look at the official Apple sample for Reachability:
https://developer.apple.com/library/content/samplecode/Reachability/Introduction/Intro.html
var netStatus = reachability.currentReachabilityStatus()
var connectionRequired = reachability.connectionRequired()
var statusString = ""
switch netStatus {
case NotReachable:
break
case ReachableViaWWAN:
//DATA
break
case ReachableViaWiFi:
//WIFI
break
}
You can use this method to check:
First you import this framework:
import SystemConfiguration.CaptiveNetwork
func isWifiEnabled() -> Bool {
var hasWiFiNetwork: Bool = false
let interfaces: NSArray = CFBridgingRetain(CNCopySupportedInterfaces()) as! NSArray
for interface in interfaces {
// let networkInfo = (CFBridgingRetain(CNCopyCurrentNetworkInfo(((interface) as! CFString))) as! NSDictionary)
let networkInfo: [AnyHashable: Any]? = CFBridgingRetain(CNCopyCurrentNetworkInfo(((interface) as! CFString))) as? [AnyHashable : Any]
if (networkInfo != nil) {
hasWiFiNetwork = true
break
}
}
return hasWiFiNetwork;
}
This method was working while I was using Swift 1.2. But now, I had to update to Xcode and I had to switch my language to Swift 2. This is the method from swift 1.2 which I used well ;
static func findById(idToFind : Int64) -> T? {
let query = table.filter(id == idToFind)
var results: Payment?
if let item = query.first {
results : T = Payment(id: item[id], imageName: item[image], type: item[type], deliveredPriceStr: item[deliveredPrice], orderID: item[orderId])
}
return results
}
Now I modified it for Swift 2 but couldn't manage;
static func findById(idToFind : Int64) -> T? {
let query = table.filter(id == idToFind)
do {
let query = try table.filter(id == idToFind)
let item = try SQLiteDataStore.sharedInstance.SADB.pluck(query)
if try item != nil {
let results : T = Payment(id: item[id], imageName: item[image], type: item[type], deliveredPriceStr: item[deliveredPrice], orderID: item[orderId])
} else {
print("item not found")
}
} catch {
print("delete failed: \(error)")
}
}
return results
}
And I'm getting this error : "Cannot subscript a value of type Row" . My item's data type seems like changed to Row. How can I parse it ? What should I do ?
PS: I'm using swift2 branch.
Finally I figured out how to get values. It's easy now the row item has get method on swift-2 branch. So new method is ;
static func findById(idToFind : Int64) -> T? {
let query = table.filter(id == idToFind)
var results : T?
do {
let query = table.filter(id == idToFind)
let item = SQLiteDataStore.sharedInstance.SADB.pluck(query)
if try item != nil {
results = Payment( id: (item?.get(id))!, imageName: (item?.get(image))!, type: (item?.get(type))!, deliveredPriceStr: (item?.get(deliveredPrice))!, orderID: (item?.get(orderId))!)
} else {
print("item not found")
}
}
catch {
print("delete failed: \(error)")
}
return results
}
Hope that this helps someone.
Trying to get the SSID of current device. I have found plenty of examples on how to do it however I am struggling with getting the CNCopySupportedInterfaces to autocomplete. I have 'import SystemConfiguration' at the top of my swift file but no success. Can't seem to figure out what I am doing wrong.
iOS 12
You must enable Access WiFi Information from capabilities.
Important
To use this function in iOS 12 and later, enable the Access WiFi Information capability for your app in Xcode. When you enable this capability, Xcode automatically adds the Access WiFi Information entitlement to your entitlements file and App ID. Documentation link
You need: import SystemConfiguration.CaptiveNetwork
Underneath the covers, CaptiveNetwork is a C header file (.h) that is within the SystemConfiguration framework:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/System/Library/Frameworks/SystemConfiguration.framework/Headers/CaptiveNetwork.h
If you know Objective-C, this goes into more depth:
iPhone get SSID without private library
You have to use the awkward syntax to bridge from any pure C API, so the following is required:
for interface in CNCopySupportedInterfaces().takeRetainedValue() as! [String] {
println("Looking up SSID info for \(interface)") // en0
let SSIDDict = CNCopyCurrentNetworkInfo(interface).takeRetainedValue() as! [String : AnyObject]
for d in SSIDDict.keys {
println("\(d): \(SSIDDict[d]!)")
}
}
ADDENDUM FOR SWIFT 2.2 and 3.0
The CFxxx datatypes are now bridged to native Objective-C runtime, eliminating the head-scratching retain calls. However, nullable pointers give rise to Optionals, so things don't get any shorter. At least, it's fairly clear what's going on, plus the nil helps us identify the simulator. The other answer uses an awful lot of bit-casting and unsafe operations which seems non-Swiftian, so I offer this.
func getInterfaces() -> Bool {
guard let unwrappedCFArrayInterfaces = CNCopySupportedInterfaces() else {
print("this must be a simulator, no interfaces found")
return false
}
guard let swiftInterfaces = (unwrappedCFArrayInterfaces as NSArray) as? [String] else {
print("System error: did not come back as array of Strings")
return false
}
for interface in swiftInterfaces {
print("Looking up SSID info for \(interface)") // en0
guard let unwrappedCFDictionaryForInterface = CNCopyCurrentNetworkInfo(interface) else {
print("System error: \(interface) has no information")
return false
}
guard let SSIDDict = (unwrappedCFDictionaryForInterface as NSDictionary) as? [String: AnyObject] else {
print("System error: interface information is not a string-keyed dictionary")
return false
}
for d in SSIDDict.keys {
print("\(d): \(SSIDDict[d]!)")
}
}
return true
}
Output on success:
SSIDDATA: <57696c6d 79>
BSSID: 12:34:56:78:9a:bc
SSID: YourSSIDHere
In Swift 2.0 / iOS 9 the API CaptiveNetwork is (nearly) gone or depreciated. I contacted Apple regarding this problem and I thought we could (or should) use the NEHotspotHelper instead. I got a respond from Apple today: One should continue to use CaptiveNetwork and the two relevant APIs (even tough there marked depreciated):
CNCopySupportedInterfaces
CNCopyCurrentNetworkInfo
The user braime posted an updated code-snippet for this problem on Ray Wenderlich forums:
let interfaces:CFArray! = CNCopySupportedInterfaces()
for i in 0..<CFArrayGetCount(interfaces){
let interfaceName: UnsafePointer<Void>
= CFArrayGetValueAtIndex(interfaces, i)
let rec = unsafeBitCast(interfaceName, AnyObject.self)
let unsafeInterfaceData = CNCopyCurrentNetworkInfo("\(rec)")
if unsafeInterfaceData != nil {
let interfaceData = unsafeInterfaceData! as Dictionary!
currentSSID = interfaceData["SSID"] as! String
} else {
currentSSID = ""
}
}
Works perfect for me.
Swift:
import SystemConfiguration.CaptiveNetwork
func currentSSIDs() -> [String] {
guard let interfaceNames = CNCopySupportedInterfaces() as? [String] else {
return []
}
return interfaceNames.flatMap { name in
guard let info = CNCopyCurrentNetworkInfo(name as CFString) as? [String:AnyObject] else {
return nil
}
guard let ssid = info[kCNNetworkInfoKeySSID as String] as? String else {
return nil
}
return ssid
}
}
Then print(currentSSIDs()), not working on simulator, only real devices.
Taken from https://forums.developer.apple.com/thread/50302
func getInterfaces() -> String? {
var ssid: String?
if let interfaces = CNCopySupportedInterfaces() as NSArray? {
for interface in interfaces {
if let interfaceInfo = CNCopyCurrentNetworkInfo(interface as! CFString) as NSDictionary? {
ssid = interfaceInfo[kCNNetworkInfoKeySSID as String] as? String
break
}
}
}
return ssid
}
In iOS 12 and up you will need to enable the Access WiFi Information capability for your app in order to get the ssid