iOS将电话号码转换为国际格式

在我的iOS应用程序中,我必须转换电话号码(在联系人中拍摄)并以国际格式转换(使用外部库自动发送短信).我看到 libPhoneNumber,但问题是我们必须输入国家代码,应用程序必须在所有(几乎)国家/地区工作,所以我不知道用户的国家/地区是什么.

以下是图书馆的工作方式:

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))

最佳答案 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];

}

点赞