iOS将电话号码转换为国际格式 [英] iOS Convert phone number to international format

查看:766
本文介绍了iOS将电话号码转换为国际格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的iOS应用中,我必须转换一个电话号码(在联系人中获取)并转换为国际格式(以使用extern库自动发送SMS).我看到了 libPhoneNumber ,但问题是我们必须输入国家/地区代码,而应用程序必须在(几乎)所有国家/地区工作,因此我不知道用户所在的国家/地区.

In my iOS app I have to convert a phone number (taken in the contacts) and convert it in international format (to send SMS automatically with an extern library). I saw libPhoneNumber but the problem is that we have to enter the country code, and the app have to work in all (almost) countries, so I don't know what is the user's country.

库的工作原理如下:

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".

formattedPhoneNumberSubstring takes a partial phone number string and formats it as the beginning of a properly formatted international number, e.g. "16463" turns to "+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];

}

这篇关于iOS将电话号码转换为国际格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆