Search code examples
iosswiftkey-valuecore-telephony

CTTelephonyNetworkInfo returning nil on iOS 12


I have the following code:

let networkStatus = CTTelephonyNetworkInfo()

func getCellularInfo() {
    if #available(iOS 12.0, *) {
        var info = networkStatus.serviceSubscriberCellularProviders
        if let aKey = networkStatus.value(forKey: "serviceSubscriberCellularProvider") {
            print("aKey: \(aKey)")
        }
    }
}

This code retuns:

aKey: { 0000000100000001 = "CTCarrier (0x28282e610) {\n\tCarrier name: [Vodacom]\n\tMobile Country Code: [655]\n\tMobile Network Code:[01]\n\tISO Country Code:[za]\n\tAllows VOIP? [YES]\n}\n"; }

I am not familiar with this method, how do I obtain the values associated with the keys, for example \n\tMobile Country Code: [655]/n/


Solution

  • The property serviceSubscriberCellularProviders on CTTelephonyNetworkInfo returns a dictionary of CTCarrier objects keyed by String.

    var serviceSubscriberCellularProviders: [String : CTCarrier]?

    You can see that in your claimed output: CTCarrier (0x28282e610) {....

    How you got that output is unclear as your posted code, while syntax correct, never uses the generated info dictionary variable.

    So with correct code (assuming serviceSubscriberCellularProvider is the key):

    let networkStatus = CTTelephonyNetworkInfo()
    if let info = networkStatus.serviceSubscriberCellularProviders, 
       let carrier = info["serviceSubscriberCellularProvider"] {
        //work with carrier object
        print("MNC = \(carrier.mobileNetworkCode)")
    }
    

    But that doesn't seem to work on a single SIM iPhone 7 running iOS 12.0.1. serviceSubscriberCellularProviders is nil. Possibly the newer phones with dual-SIM hardware will react differently.

    The deprecated property still works however.

    let networkStatus = CTTelephonyNetworkInfo()
    if let carrier = networkStatus.subscriberCellularProvider {
        print("MNC = \(carrier.mobileNetworkCode ?? "NO CODE")")
    }