iOS 9: get CNContact country code and phone number

后端 未结 5 1248
-上瘾入骨i
-上瘾入骨i 2020-12-09 10:42

I want to get the country code and phone number from CNContact on iOS 9. I tried many things but couldn\'t find a way. The best result I achieved is printing:



        
相关标签:
5条回答
  • 2020-12-09 11:07

    Objective-C:

    [number.value valueForKey:@"countryCode"]
    

    Swift:

    number.value.valueForKey("countryCode") as? String
    

    valueForKey is not private, and your app will not get rejected.

    0 讨论(0)
  • 2020-12-09 11:13

    /* Get only first mobile number */

        let MobNumVar = (contact.phoneNumbers[0].value as! CNPhoneNumber).valueForKey("digits") as! String
        print(MobNumVar)
    

    /* Get all mobile number */

        for ContctNumVar: CNLabeledValue in contact.phoneNumbers
        {
            let MobNumVar  = (ContctNumVar.value as! CNPhoneNumber).valueForKey("digits") as? String
            print(MobNumVar!)
        }
    

    /* Get mobile number with mobile country code */

        for ContctNumVar: CNLabeledValue in contact.phoneNumbers
        {
            let FulMobNumVar  = ContctNumVar.value as! CNPhoneNumber
            let MccNamVar = FulMobNumVar.valueForKey("countryCode") as? String
            let MobNumVar = FulMobNumVar.valueForKey("digits") as? String
    
            print(MccNamVar!)
            print(MobNumVar!)
        }
    
    0 讨论(0)
  • 2020-12-09 11:13

    To get Country code you can use this:

    (contact.phoneNumbers[0].value ).value(forKey: "countryCode") as! String
    

    in for loop, and key; "digits" is to get full phone number.

    0 讨论(0)
  • 2020-12-09 11:14

    Unfortunately you can't get them since they are private.

    let numberValue = number.value
    
    let countryCode = numberValue.valueForKey("countryCode") as? String
    let digits = numberValue.valueForKey("digits") as? String
    

    This works but if you do something in this lines your app will most likely be rejected.

    You can see all the nice stuff you could use here.

    If you don't plan on uploading your app to the store the solution above is OK, otherwise I'd stick with some kind of regex knowing it can break in the future:

    countryCode=(\w{2}),.*digits=(.+)>$
    
    0 讨论(0)
  • 2020-12-09 11:16

    They two members can be accessed via valueForKey:

    let countryCode = number.valueForKey("countryCode") as? String
    let digits = number.valueForKey("digits") as? String
    

    Please note that due to the fact that these two fields are part of a private API, there's no guarantee that in the future versions of the Contacts framework they won't be removed/replaced.

    0 讨论(0)
提交回复
热议问题