IOS Convert Phone Number to International Format

In my iOS application, I need to convert the phone number (made in contacts) and convert it to the international format (for automatically sending SMS using the extern library). I saw libPhoneNumber , but the problem is that we have to enter the country code, and the application should work in all (almost) countries, so I do not know what a user country is.

Here's how the library works:

let phoneUtil = NBPhoneNumberUtil()
let phoneNumberConverted = try phoneUtil.parse("0665268242", defaultRegion: "FR") // So I don't know the country of the user here
print(try? phoneUtil.format(phoneNumberConverted, numberFormat: NBEPhoneNumberFormat.INTERNATIONAL))
+4
source share
3 answers

formattedPhoneNumberSubstring , . "16463" "+1 646-3".

NSString *formattedPhoneNumberSubstring(NSString *phoneNumber) {
NBPhoneNumberUtil *phoneUtil = [NBPhoneNumberUtil sharedInstance];
phoneNumber = [phoneUtil normalizeDigitsOnly:phoneNumber];
NSString *nationalNumber;
NSNumber *countryCode = [phoneUtil extractCountryCode:phoneNumber nationalNumber:&nationalNumber];
if ([countryCode isEqualToNumber:@0])
    return phoneNumber;

NSString *regionCode = [[phoneUtil regionCodeFromCountryCode:countryCode] objectAtIndex:0];
NSString *paddedNationalNumber = [nationalNumber stringByPaddingToLength:15 withString:@"0" startingAtIndex:0];
NSString *formatted;
NSString *formattedSubstr;
for (int i=0; i < paddedNationalNumber.length; i++) {
    NSError *error = nil;
    formattedSubstr = [phoneUtil format:[phoneUtil parse:[paddedNationalNumber substringToIndex:i] defaultRegion:regionCode error:&error]
                           numberFormat:NBEPhoneNumberFormatINTERNATIONAL error:&error];
    if (getExtraCharacters(formattedSubstr) > getExtraCharacters(formatted)) // extra characters means more formatted
        formatted = formattedSubstr;
}

// Preparing the buffer for phoneNumber
unichar phoneNumberBuffer[phoneNumber.length+1];
[phoneNumber getCharacters:phoneNumberBuffer range:NSMakeRange(0, phoneNumber.length)];

// Preparing the buffer for formatted
unichar formattedBuffer[formatted.length+1];
[formatted getCharacters:formattedBuffer range:NSMakeRange(0, formatted.length)];

int j=0;
for(int i = 0; i < phoneNumber.length && j < formatted.length; i++) {
    while(formattedBuffer[j] != phoneNumberBuffer[i]) j++;
    j++;
}

return [formatted substringToIndex:j];

}

+1

, , . . _, .

0

, .

, , . , - , Im , . , , , .

, , . SIM- . . , - Swift- Ive:

let networkInfo = CTTelephonyNetworkInfo()
if let carrier = networkInfo.subscriberCellularProvider {
    NSLog("Carrier: \(carrier.carrierName)")
    NSLog("ISO: \(carrier.isoCountryCode)")
    NSLog("MCC: \(carrier.mobileCountryCode)")
    NSLog("MNC: \(carrier.mobileNetworkCode)")
}

The ISO country code can be used to find the country code for dialing; an example table is in the answer above.

0
source

Source: https://habr.com/ru/post/1622330/


All Articles