Giter Club home page Giter Club logo

libphonenumber-ios's Introduction

CocoaPods CocoaPods Travis Coveralls Carthage compatible

libPhoneNumber for iOS

  • NBPhoneNumberUtil
  • NBAsYouTypeFormatter

ARC only

Update Log

https://github.com/iziz/libPhoneNumber-iOS/wiki/Update-Log

Issue

You can check phone number validation using below link. https://rawgit.com/googlei18n/libphonenumber/master/javascript/i18n/phonenumbers/demo-compiled.html

Please report, if the above results are different from this iOS library. Otherwise, please create issue to following link below to request additional telephone numbers formatting rule. https://github.com/google/libphonenumber/issues

Metadata in this library was generated from that. so, you should change it first. :)

Install

Using CocoaPods

source 'https://github.com/CocoaPods/Specs.git'
pod 'libPhoneNumber-iOS', '~> 0.8'
Installing libPhoneNumber Geocoding Features
pod 'libPhoneNumberGeocoding', :git => 'https://github.com/CocoaPods/Specs.git'

Using Carthage

Carthage is a decentralized dependency manager that automates the process of adding frameworks to your Cocoa application.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate libPhoneNumber into your Xcode project using Carthage, specify it in your Cartfile:

github "iziz/libPhoneNumber-iOS"

And set the Embedded Content Contains Swift to "Yes" in your build settings.

Setting up manually

Add source files to your projects from libPhoneNumber - Add "Contacts.framework"

See sample test code from

[libPhoneNumber-iOS/libPhoneNumberTests/ ... Test.m] (https://github.com/iziz/libPhoneNumber-iOS/tree/master/libPhoneNumberTests)

Usage - NBPhoneNumberUtil

 NBPhoneNumberUtil *phoneUtil = [NBPhoneNumberUtil sharedInstance];
 NSError *anError = nil;
 NBPhoneNumber *myNumber = [phoneUtil parse:@"6766077303"
                              defaultRegion:@"AT" error:&anError];
 if (anError == nil) {
     NSLog(@"isValidPhoneNumber ? [%@]", [phoneUtil isValidNumber:myNumber] ? @"YES":@"NO");

     // E164          : +436766077303
     NSLog(@"E164          : %@", [phoneUtil format:myNumber
                                       numberFormat:NBEPhoneNumberFormatE164
                                              error:&anError]);
     // INTERNATIONAL : +43 676 6077303
     NSLog(@"INTERNATIONAL : %@", [phoneUtil format:myNumber
                                       numberFormat:NBEPhoneNumberFormatINTERNATIONAL
                                              error:&anError]);
     // NATIONAL      : 0676 6077303
     NSLog(@"NATIONAL      : %@", [phoneUtil format:myNumber
                                       numberFormat:NBEPhoneNumberFormatNATIONAL
                                              error:&anError]);
     // RFC3966       : tel:+43-676-6077303
     NSLog(@"RFC3966       : %@", [phoneUtil format:myNumber
                                       numberFormat:NBEPhoneNumberFormatRFC3966
                                              error:&anError]);
 } else {
     NSLog(@"Error : %@", [anError localizedDescription]);
 }

 NSLog (@"extractCountryCode [%@]", [phoneUtil extractCountryCode:@"823213123123" nationalNumber:nil]);

 NSString *nationalNumber = nil;
 NSNumber *countryCode = [phoneUtil extractCountryCode:@"823213123123" nationalNumber:&nationalNumber];

 NSLog (@"extractCountryCode [%@] [%@]", countryCode, nationalNumber);
Output
2014-07-06 12:39:37.240 libPhoneNumberTest[1581:60b] isValidPhoneNumber ? [YES]
2014-07-06 12:39:37.242 libPhoneNumberTest[1581:60b] E164          : +436766077303
2014-07-06 12:39:37.243 libPhoneNumberTest[1581:60b] INTERNATIONAL : +43 676 6077303
2014-07-06 12:39:37.243 libPhoneNumberTest[1581:60b] NATIONAL      : 0676 6077303
2014-07-06 12:39:37.244 libPhoneNumberTest[1581:60b] RFC3966       : tel:+43-676-6077303
2014-07-06 12:39:37.244 libPhoneNumberTest[1581:60b] extractCountryCode [82]
2014-07-06 12:39:37.245 libPhoneNumberTest[1581:60b] extractCountryCode [82] [3213123123]

with Swift

Case (1) with Framework
import libPhoneNumberiOS
Case (2) with Bridging-Header
// Manually added
#import "NBPhoneNumberUtil.h"
#import "NBPhoneNumber.h"

// CocoaPods (check your library path)
#import "libPhoneNumber_iOS/NBPhoneNumberUtil.h"
#import "libPhoneNumber_iOS/NBPhoneNumber.h"

// add more if you want...
Case (3) with CocoaPods

import libPhoneNumber_iOS

- in swift class file
2.x
override func viewDidLoad() {
    super.viewDidLoad()

    guard let phoneUtil = NBPhoneNumberUtil.sharedInstance() else {
        return
    }

    do {
        let phoneNumber: NBPhoneNumber = try phoneUtil.parse("01065431234", defaultRegion: "KR")
        let formattedString: String = try phoneUtil.format(phoneNumber, numberFormat: .E164)

        NSLog("[%@]", formattedString)
    }
    catch let error as NSError {
        print(error.localizedDescription)
    }
}

Usage - NBAsYouTypeFormatter

 NBAsYouTypeFormatter *f = [[NBAsYouTypeFormatter alloc] initWithRegionCode:@"US"];
    NSLog(@"%@", [f inputDigit:@"6"]); // "6"
    NSLog(@"%@", [f inputDigit:@"5"]); // "65"
    NSLog(@"%@", [f inputDigit:@"0"]); // "650"
    NSLog(@"%@", [f inputDigit:@"2"]); // "650 2"
    NSLog(@"%@", [f inputDigit:@"5"]); // "650 25"
    NSLog(@"%@", [f inputDigit:@"3"]); // "650 253"

    // Note this is how a US local number (without area code) should be formatted.
    NSLog(@"%@", [f inputDigit:@"2"]); // "650 2532"
    NSLog(@"%@", [f inputDigit:@"2"]); // "650 253 22"
    NSLog(@"%@", [f inputDigit:@"2"]); // "650 253 222"
    NSLog(@"%@", [f inputDigit:@"2"]); // "650 253 2222"
    // Can remove last digit
    NSLog(@"%@", [f removeLastDigit]); // "650 253 222"

    NSLog(@"%@", [f inputString:@"16502532222"]); // 1 650 253 2222

libPhoneNumberGeocoding

For more information on libPhoneNumberGeocoding and its usage, please visit libPhoneNumberGeocoding for more information.

libPhoneNumberShortNumber

For more information on libPhoneNumberShortNumber and its usage, please visit libPhoneNumberShortNumber for more information.

Visit libphonenumber for more information or mail ([email protected])

libphonenumber-ios's People

Contributors

alexterente avatar artyom-stv avatar aterite avatar cassianodialpad avatar changsung avatar chrispark-google avatar cmkilger avatar dmaclach avatar egoldfarb avatar fawkeswei avatar hashier avatar iziz avatar jishnum avatar johennes avatar jthehe avatar karimhm avatar ky1ejs avatar lickel avatar marmelroy avatar meccatol avatar meiwin avatar moshegottlieb avatar nghuiqin avatar pauluhn avatar paween avatar rastaarh avatar rishatshamsutdinov avatar simx avatar toblerpwn avatar youminkim avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

libphonenumber-ios's Issues

I can't validate pakistani numbers

I'm trying to validate pakistani numbers but I'm "false" when I check if my phone number is valid.

The number I'm trying to check is: +923406171134. I also tested it in http://libphonenumber.appspot.com and I'm getting "valid" as result:

Phone Number entered: +923406171134
defaultCountry entered: GB
Language entered: en
Parsing Result
country_code 92
national_number 3406171134
extension
country_code_source FROM_NUMBER_WITH_PLUS_SIGN
italian_leading_zero false
raw_input +923406171134
Validation Results
Result from isPossibleNumber() true
Result from isValidNumber() true
Result from isValidNumberForRegion() false
Phone Number region PK
Result from getNumberType() MOBILE
Formatting Results
E164 format +923406171134
Original format +92 340 6171134
National format 0340 6171134
International format +92 340 6171134
Out-of-country format from US 011 92 340 6171134
Out-of-country format from CH 00 92 340 6171134
AsYouTypeFormatter Results
Char entered: '+' Output: +
Char entered: '9' Output: +9
Char entered: '2' Output: +92
Char entered: '3' Output: +92 3
Char entered: '4' Output: +92 34
Char entered: '0' Output: +92 340
Char entered: '6' Output: +92 340 6
Char entered: '1' Output: +92 340 61
Char entered: '7' Output: +92 340 617
Char entered: '1' Output: +92 340 6171
Char entered: '1' Output: +92 340 61711
Char entered: '3' Output: +92 340 617113
Char entered: '4' Output: +92 340 6171134
PhoneNumberOfflineGeocoder Results
Location Pakistan
PhoneNumberToTimeZonesMapper Results
Time zone(s) [Asia/Karachi]
PhoneNumberToCarrierMapper Results
Carrier Telenor

Deprecation of singleton

I'm wondering why you deprecated the sharedInstance… methods. Didn't it make sense to use the shared instance for caching purposes?
Should I really create a new instance for each phone number check?

Would be great if you could elaborate on the reasoning and how we should change our code when using the lib.

Swift problem

Hello,

I use the following code

var errorPointer:NSError?
var number:NBPhoneNumber = phoneUtil.parse(sender.text, defaultRegion: region, error: &errorPointer)

and I get the following error :
fatal error: unexpectedly found nil while unwrapping an Optional value

Do you know where it comes from ?

Thx

Separate and Remove Depencies from Implementation Code on Test Code

Hello! Thank you for the project. In our project we don't use CocoaPods, thus Framework support is necessary for us. It would be great to have this, or a static library.

Also, I tried to import the project and there seems to be unnecessary imports e.g. NBMetadataCoreTest.h. Why are the tests included in the actual code? It would be better if the tests were separated from the actual code.

If these improvements pique your interest I would be open to creating and submitting a pull request for you. :) Thanks in advance for your feedback.

Prevent non-local number without + or 00 getting the local country code

Hi all,

Thank you for sharing this great library,

My app needs to read a phone number from the device address book, format it, and send it to my server.

So for example if I'm from Spain (+34) and one of my contacts is a US number (9144484373), I want that the final result for all the following options will be the same:

+19144484373
009144484373
19144484373

===> all should end up to: 19144484373

I'm using the following code to get the final result:

NBPhoneNumberUtil *phoneUtil = [NBPhoneNumberUtil sharedInstance];
 NBPhoneNumber *myNumber = [phoneUtil parse:@"+19144484373" defaultRegion:@"ES" error:nil];

NSString *finalNum = [NSString stringWithFormat:@"%@%@", @(myNumber.countryCode), @(myNumber.nationalNumber)];
 NSLog(@"final num: %@", finalNum);

myNumber = [phoneUtil parse:@"19144484373" defaultRegion:@"ES" error:nil];
finalNum = [NSString stringWithFormat:@"%@%@", @(myNumber.countryCode), @(myNumber.nationalNumber)];
 NSLog(@"final num: %@", finalNum);

so for +19144484373 (or 0019144484373) the final output is:
final num: 19144484373

but for 19144484373 the final output is:
final num: 3419144484373

Obviously the last one is incorrect, and I understand that from the beginning the number 19144484373 was saved in invalid format (you cant really call the num without the + or 00)
But still I would like to be able to handle those numbers also, is it possible to know that this num 19144484373 is actually 19144484373 and not 3419144484373 ?

thanks

Access to the support regions

Would be great to have access to the regions supported by the library. So something like this in NBPhoneNumberUtil.m.

- (NSArray*)supportedRegions
{
    return [[_mapCCode2CN allKeys] sortedArrayUsingComparator:^(NSString* lhs, NSString* rhs){
        NSString* lhsCountry = [[NSLocale currentLocale] displayNameForKey: NSLocaleCountryCode value:lhs];
        NSString* rhsCountry = [[NSLocale currentLocale] displayNameForKey: NSLocaleCountryCode value:rhs];
        return [lhsCountry compare:rhsCountry];
    }];
}

Swift usage example ?

Thank you for your library.

How to setup existing xcode project for using with Swift manually ?
Is it possible to get some code snippets for using with Swift ?

Thanks in advance.

Library has severe memory allocation issues

This library has memory allocation issues, it will continue to consume more and more memory if you give it lots of phone numbers. If you process a list of phone numbers of 30K you will see it allocate 450MBs of memory on an iPhone 5S, and due to the singleton, then never release it. The situation only gets worse if you alloc, then init the library without the singleton. The library is obviously storing something in an NSMutableArray or NSMutableString, and never deletes them.
It's a very useful library, but if your processing a large number of iPhone AddressBook contacts it will crash your application when it processes a large number of phone numbers.

Formatting issues with CN or HK regions

So this is weird...when I type in the following code as a test, I noticed that the formatting is off:

    NBAsYouTypeFormatter *f = [[NBAsYouTypeFormatter alloc] initWithRegionCode:@"CN"];
    NSLog(@"%@", [f inputDigit:@"1"]); // "1"
    NSLog(@"%@", [f inputDigit:@"2"]); // "12"
    NSLog(@"%@", [f inputDigit:@"3"]); // "123"

    NSLog(@"%@", [f inputDigit:@"4"]); // "1234"
    NSLog(@"%@", [f inputDigit:@"5"]); // "12345"
    NSLog(@"%@", [f inputDigit:@"6"]); // "12345 6"
    NSLog(@"%@", [f inputDigit:@"7"]); // "12345 67"

    NSLog(@"%@", [f inputDigit:@"8"]); // "12345 678"
    NSLog(@"%@", [f inputDigit:@"9"]); // "12345 678 9"
    NSLog(@"%@", [f inputDigit:@"0"]); // "1234567890"
    NSLog(@"%@", [f inputDigit:@"0"]); // "12345678900"

Anyone else run into this issue?

64 bits warnings

Hi, Any plan to convert the code to 64 bits?

I i have time i can do that in a pull request, just hope the tests would pass :D

64 Bit build

There are a number of warnings when building for 64bit with integers.

Crashes after updating to 0.8.2

After updating to 0.8.2 I get many crashes

Crashed: com.apple.root.background-qos
EXC_BAD_ACCESS KERN_INVALID_ADDRESS at 0x0000000072657880

libobjc.A.dylib 0x000000019480bbd0 objc_msgSend + 16
1 CoreFoundation 0x0000000183f97398 -[__NSCFString isEqualToString:] + 156
2 LessWalk AB 0x00000001004b5410 +NBMetadataHelper getMetadataForRegion:
3 LessWalk AB 0x00000001004c29f8 -NBPhoneNumberUtil getMetadataForRegionOrCallingCode:regionCode:
4 LessWalk AB 0x00000001004c7ad4 -NBPhoneNumberUtil getNumberType:
5 LessWalk AB 0x00000001000ea028 -PhoneNumberService isMobilePhoneNumber:
6 LessWalk AB 0x00000001000c5e54 __34-[ContactsService contactsByName:]_block_invoke (ContactsService.m:71)
7 LessWalk AB 0x00000001000c6d94 -ContactsService enumerateAddressBookByName:recordHandler:
8 LessWalk AB 0x00000001000c5b68 -ContactsService contactsByName:
9 LessWalk AB 0x00000001000c8078 -ContactsService findAllContacts
10 LessWalk AB 0x00000001000adf00 -HomeViewController loadContacts
11 LessWalk AB 0x00000001000b3584 __57-[HomeViewController onContentItemWasLoadedNotification:]_block_invoke522 (HomeViewController.m:697)
12 LessWalk AB 0x00000001000b9e88 __41-[UIView(Async) runInBackground:runInUI:]_block_invoke (UIView+Async.m:26)
13 libdispatch.dylib 0x0000000194e3d3ac _dispatch_call_block_and_release + 24
14 libdispatch.dylib 0x0000000194e3d36c _dispatch_client_callout + 16
15 libdispatch.dylib 0x0000000194e4940c _dispatch_root_queue_drain + 1152
16 libdispatch.dylib 0x0000000194e4a75c _dispatch_worker_thread3 + 108
17 libsystem_pthread.dylib 0x00000001950192e4 _pthread_wqthread + 816

NBAsYouTypeFormatter: Lacks support for handling changes to the middle of a phone number string

If I use the NBAsYouTypeFormatter to format text as it is typed into a UITextField via textField:shouldChangeCharactersInRange:replacementString: there doesn't appear to be any methods that support changing digits in the middle of a phone number string, only support for adding or removing digits from the tail.

Something like:

- (NSString *)inputDigit:(NSString *)nextChar atPosition:(NSUInteger)position;

SIGABRT in [NBMetadataHelper getMetadataForRegion:] in 0.8.4

It looks like this issue was not fully resolved...got this crash:


Thread 31 Crashed:
0   libsystem_kernel.dylib               0x0000000194ae3270 __pthread_kill + 8
1   libsystem_pthread.dylib              0x0000000194b81228 pthread_kill + 108
2   libsystem_c.dylib                    0x0000000194a5ab18 abort + 108
3   libsystem_malloc.dylib               0x0000000194b1e3e4 nanozone_error + 316
4   libsystem_malloc.dylib               0x0000000194b1d2f8 nano_free + 188
5   CoreFoundation                       0x0000000183c3b2b8 __CFStringDeallocate + 188
6   CoreFoundation                       0x0000000183b492b4 CFRelease + 324
7   App                                0x00000001006291b0 +[NBMetadataHelper getMetadataForRegion:] (NBMetadataHelper.m:228)
8   App                                0x00000001006364f4 -[NBPhoneNumberUtil getMetadataForRegionOrCallingCode:regionCode:] (NBPhoneNumberUtil.m:1257)
9   App                                0x0000000100635624 -[NBPhoneNumberUtil format:numberFormat:] (NBPhoneNumberUtil.m:1091)
10  App                                0x00000001006350ac -[NBPhoneNumberUtil format:numberFormat:error:] (NBPhoneNumberUtil.m:1037)
11  App                                0x0000000100116398 -[NSString(Telephony) formattedPhoneNumber] (NSString+Telephony.m:65)

Any suggestions?

Thanks!
John

Wrong destination for Metadata

Metadata are currently sent to NSDocumentDirectory, this is wrong since files stocked here are sent to iCloud. Even without it, it's wrong since it's not document (word, excel...) but support files used only by the app.

You should use NSCachesDirectory (best if the files can be regenerated when missing) or NSApplicationSupportDirectory (less subject to discarding when memory is full).

Unclear method names for country/region codes

The API appears to be intermixing the terms "country code" and "region code", which is really confusing. See the example below:

NBPhoneNumberUtil *util = [NBPhoneNumberUtil sharedInstance];

// This returns a "country code" and will in this case give something like "US".
NSString *country = [[util countryCodeByCarrier] uppercaseString];

// These two methods expect "region codes", which in this case is something like "US".
self.asYouTypeFormatter = [[NBAsYouTypeFormatter alloc] initWithRegionCode:countryCode];
NSString *prefix = [util countryCodeFromRegionCode:countryCode];

// This will take a "country code" and return a "region code". In this case it takes the number 46 and returns the string "SE".
[util regionCodeFromCountryCode:@46];

SIGABRT in 0.8.3

Got a sigabrt after updating to the latest cocoapod. Not sure if this is something wrong on my end, but I'm just calling parse using the (now deprecated) singleton number formatter

Thread : Crashed: com.apple.root.default-priority
0 libsystem_kernel.dylib 0x0000000191b2658c __pthread_kill + 8
1 libsystem_pthread.dylib 0x0000000191ba916c pthread_kill + 104
2 libsystem_c.dylib 0x0000000191aba808 abort + 112
3 libsystem_malloc.dylib 0x0000000191b605c4 _nano_malloc_check_clear
4 libsystem_malloc.dylib 0x0000000191b5f548 nano_free + 252
5 CoreFoundation 0x0000000184f02ad8 __CFStringDeallocate + 192
6 CoreFoundation 0x0000000184e29f8c CFRelease + 316
7 App 0x000000010058ce64 +NBMetadataHelper getMetadataForRegion:
8 App 0x0000000100598b94 -NBPhoneNumberUtil isValidRegionCode:
9 App 0x00000001005a4830 -NBPhoneNumberUtil checkRegionForParsing:defaultRegion:
10 App 0x00000001005a54a0 -NBPhoneNumberUtil parseHelper:defaultRegion:keepRawInput:checkRegion:error:
11 App 0x00000001005a4998 -NBPhoneNumberUtil parse:defaultRegion:error:

iOS 8 issue

i'm having next issue: -[NSKeyedUnarchiver initForReadingWithData:]: data is NULL

when i'm trying to input/format phone number in iOS 8

NBAsYouTypeFormatter doesn't work

If i init a NBAsYouTypeFormatter it doesn't work.

I think it's because it calls loadMetadata: in NBPhoneNumberUtil and the unarchive doesn't work:

unarchiveData = [NSKeyedUnarchiver unarchiveObjectWithData:fileData]; in line 499 returns nil.

Any idea why this happens?

Changing classes names

Hi @iziz, i'm trying to include libPhoneNumber inside a framework i'm helping to build. To avoid crashes, when another app is using this framework and also includes your library, i'm changing the class names by adding a prefix. The problem is that when I change the classes names the library is not formatting anymore. Have any clue why ?

Crash when using from multiple threads

I'm using libPhoneNumber (installed version 0.8.5 from CocoaPods) from multiple threads. Each thread creates its own instance of NBPhoneNumberUtil. Now I'm seeing a rare crash where one thread is in the middle of a NBPhoneNumberUtil operation. The other has just finished it and is crashing in the release/teardown of NBPhoneNumberUtil. At least that's how it looks like.

This is my thread with the NBPhoneNumberUtil operation in progress:

0   libsystem_platform.dylib             0x00000001947092f8 _platform_memmove + 168
1   libicucore.A.dylib                   0x00000001939094c4 utext_openCharacterIterator + 2644
2   libicucore.A.dylib                   0x0000000193908f9c utext_openCharacterIterator + 1324
3   libicucore.A.dylib                   0x00000001939084e8 utext_clone + 28
4   libicucore.A.dylib                   0x00000001939bcba4 icu::RegexMatcher::reset(UText*) + 60
5   libicucore.A.dylib                   0x00000001939fd6e8 uregex_setText + 196
6   Foundation                           0x00000001835323e0 -[NSRegularExpression(NSMatching) enumerateMatchesInString:options:range:usingBlock:] + 1884
7   Foundation                           0x0000000183531c3c -[NSRegularExpression(NSMatching) firstMatchInString:options:range:] + 140
8   WhereToKit                           0x00000001005e6360 -[NBPhoneNumberUtil matchesEntirely:string:] (NBPhoneNumberUtil.m:3850)
9   WhereToKit                           0x00000001005e0c28 -[NBPhoneNumberUtil isNumberMatchingDesc:numberDesc:] (NBPhoneNumberUtil.m:2255)
10  WhereToKit                           0x00000001005e0628 -[NBPhoneNumberUtil getNumberTypeHelper:metadata:] (NBPhoneNumberUtil.m:2146)
11  WhereToKit                           0x00000001005e0e90 -[NBPhoneNumberUtil isValidNumberForRegion:regionCode:] (NBPhoneNumberUtil.m:2322)
12  WhereToKit                           0x00000 001005e0ca4 -[NBPhoneNumberUtil isValidNumber:] (NBPhoneNumberUtil.m:2273)

This is the crashing thread where I just finished using NBPhoneNumberUtil:

Thread 20 Crashed:
0   libobjc.A.dylib                      0x0000000193eebf04 objc_destructInstance + 40
1   libobjc.A.dylib                      0x0000000193eebf90 object_dispose + 24
2   libobjc.A.dylib                      0x0000000193ef8e28 objc_object::sidetable_release(bool) + 224
3   WhereToKit                           0x00000001003c2724 -[NSString(Additions) isValidPhoneNumberCountryCode:] (NSString+Additions.m:142)

Here's the general crash information:

Exception Type:  SIGSEGV
Exception Codes: SEGV_ACCERR at 0x1a50093358c
Crashed Thread:  20

Application Specific Information:
Selector name found in current argument registers: dealloc

Is the use of libPhoneNumber from multiple threads not supported? The recent refactoring of moving away from the singleton suggested to me that it's fine to use it from multiple threads as long as the NBPhoneNumberUtil objects are not shared.

Possible Bug in maybeExtractCountryCode...

Could this be bug in the library?

In this function

maybeExtractCountryCode:(NSString*)number metadata:(NBPhoneMetaData*)defaultRegionMetadata nationalNumber:(NSString**)nationalNumber keepRawInput:(BOOL)keepRawInput phoneNumber:(NBPhoneNumber**)phoneNumber error:(NSError**)error

We do a check on line:3149
if (fullNumber.length <= MIN_LENGTH_FOR_NSN_) { // Return an error since the number is too short }

But our MIN_LENGTH_FOR_NSN == 2.

So this fails for all potential country code numbers that are 2 digits long.

Eg. Brazil (+55).
Because by the time the code reaches here, the full Number length would be 2.

So Perhaps the check should be
if (fullNumber.length < MIN_LENGTH_FOR_NSN_) ... ?

Am I missing something or perhaps using this function in the wrong way?
I basically want to be able to determine the country code as a user types a number starting with + in a textfield.

Version 0.8

If you are making changes that aren't backwards compatible you should change main version number.

iOS 8.1 no country name

In iOS 8.1. I can't get country name. Please help me to fix it. Thank you. Code as follow:

NBMetadataHelper.m
NSString *country = [[NSLocale currentLocale] displayNameForKey:NSLocaleIdentifier value:identifier];
// country is nil.

Line will never be executed issue

Xcode has pointed me with a compile warning to a line that can never be executed:

//  NBAsYouTypeFormatter.m

- (NSString*)attemptToChooseFormattingPattern_
.
.
return [self maybeCreateNewTemplate_] ? [self inputAccruedNationalNumber_] : self.accruedInput_;

This is at line 1000

Bad Access error on Static Strings in iOS

I am getting bad access error on different Static NSString / Static NSDictionary / NSRegularExpression objects of library while normalising the contact number.
Randomly one of the following Static NSString / Static NSDictionary / NSRegularExpression objects get released and returns bad access error
⁃ ALL_PLUS_NUMBER_GROUPING_SYMBOLS
⁃ ALL_NORMALIZATION_MAPPINGS
⁃ ALPHA_MAPPINGS
⁃ DIALLABLE_CHAR_MAPPINGS
⁃ PLUS_CHARS_PATTERN
⁃ LEADING_PLUS_CHARS_PATTERN
⁃ CAPTURING_DIGIT_PATTERN
⁃ VALID_START_CHAR_PATTERN
⁃ SECOND_NUMBER_START_PATTERN
⁃ VALID_ALPHA_PHONE_PATTERN
⁃ UNWANTED_END_CHAR_PATTERN
⁃ EXTN_PATTERN
⁃ SEPARATOR_PATTERN
⁃ VALID_PHONE_NUMBER_PATTERN

parseWithPhoneCarrierRegion not working

parseWithPhoneCarrierRegion fails when phone number is missing country code - in this case when testing with spanish provider, es, which should translat to +34, but still fails with:

"Error Domain=INVALID_COUNTRY_CODE Code=0 "INVALID_COUNTRY_CODE:es" UserInfo=0x17426be40 {NSLocalizedDescription=INVALID_COUNTRY_CODE:es}" UserInfo=0x17007e800 {NSLocalizedDescription=Error Domain=INVALID_COUNTRY_CODE Code=0 "INVALID_COUNTRY_CODE:es" UserInfo=0x17426be40 {NSLocalizedDescription=INVALID_COUNTRY_CODE:es}}

AsYouTypeFormatter for international phone numbers

Hi, I'm using version 0.7.5, and I need an AsYouTypeFormatter for international numbers. The one in libPhoneNumber-iOS requires a defaultRegion, I tried entering nil but got an INVALID_COUNTRY_CODE error.

I thought of implementing it on my own using the existing functions in libPhoneNumber-iOS, but couldn't find enough documentation on NBPhoneNumberUtil's functions. I basically need to parse an international number (e.g. 16314032031) and format it (e.g. "+1 (631) 403-2031"), and the rest I can implement on my own. can you tell me how to do it?

Thanks, Amitai.

In some case the parse cause the crash

    0   libsystem_c.dylib               0x36b93769 usleep$NOCANCEL + 1
    1   libsystem_c.dylib               0x36bad90d abort + 81
    2   libsystem_malloc.dylib          0x36c3e3ab szone_error + 331
    3   libsystem_malloc.dylib          0x36c3e655 free_list_checksum_botch + 25
    4   libsystem_malloc.dylib          0x36c363ff tiny_malloc_from_free_list + 1023
    5   libsystem_malloc.dylib          0x36c34eb7 szone_malloc_should_clear + 219
    6   libsystem_malloc.dylib          0x36c34da7 malloc_zone_malloc + 87
    7   CoreFoundation                  0x28b281c9 __CFStringChangeSizeMultiple + 777
    8   CoreFoundation                  0x28a877a9 CFStringCreateMutableCopy + 409
    9   CoreFoundation                  0x28a9ee87 -[__NSCFString mutableCopyWithZone:] + 23
    10  Foundation 0x2979b811 -[NSString stringByReplacingOccurrencesOfString:withString:options:range:] + 145
    11  Foundation 0x2979b779 -[NSString stringByReplacingOccurrencesOfString:withString:] + 57
    12  Lion 0x005f5c6d +[NBPhoneNumberUtil normalizeNonBreakingSpace:] (NBPhoneNumberUtil.m:172)
    13  Lion 0x005fa0cb -[NBPhoneNumberUtil isViablePhoneNumber:] (NBPhoneNumberUtil.m:780)
    14  Lion 0x00601ba3 -[NBPhoneNumberUtil parseHelper:defaultRegion:keepRawInput:checkRegion:error:] (NBPhoneNumberUtil.m:3667)
    15  Lion 0x006019f9 -[NBPhoneNumberUtil parseAndKeepRawInput:defaultRegion:error:] (NBPhoneNumberUtil.m:3619)

I think the method -[NBPhoneNumberUtil buildNationalNumberForParsing: nationalNumber:] , cause this result, Had better use the NSMutableString to deal with case .

finnish phone number don't get recognised

Hello,

Finnish phones numbers don't get recognised:

NSString *nationalNumber = nil;
NSNumber *countryCode = [phoneUtil extractCountryCode:@"+358401493292" nationalNumber:&nationalNumber];

countryCode returns 0.

isViablePhoneNumber returns true for number that cannot be parsed

I am parsing the numbers in the user's contact list, and the following number causes the parse function to crash:

"927636539 nytt- (old)533021236"

In order to prevent crashes like this, I run isViablePhoneNumber on every number before attempting a parse. This works for many "numbers" that are in fact things like user account names or other text strings, but for the above number, it does return true, even though supplying that number to the parse function causes it to crash.

Crash in removeLastDigit

In code, I'm setting the phone number on a textField.

When the first keyboard input is a backspace, it then calls "removeLastDigit".

The accuratedInputWithoutFormatting = @"";

Therefore, when it tries to get a substringWithRange:NSMakeRange(0,1), it crashes with

*** Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFConstantString substringWithRange:]: Range {0, 1} out of bounds; string length 0'

isValidNumber is failing some valid numbers.

"(366) 522-8999" parsed with "US" and "+84 74 883313" parsed with "ZZ" both fail isValidNumber:

Changing the area code to something like "(818) 522-8999" for the first one passes.

"+84 74 883313" is a valid number for Vietnam - from wikipedia:
Area codes starting with 7[edit]
With effect from 5 October 2008, all telephone numbers in this area have 7 digits.
74 – Trà Vinh Province
http://en.wikipedia.org/wiki/Telephone_numbers_in_Vietnam

Debugging a little it looks like the problem is somewhere in this returning nil
NSString *regionCode = [self getRegionCodeForNumber:number];

I'm guessing this has something to do with metadata rules?

Push updated podspec

I'm not familiar with the management side of CocoaPods, but their site is still showing 0.7.2 as the latest version.

Why the phone number format pattern is different for the same country on different devices (android and iOS) using libphonenumber library?

I have used the same library for iOS and Android with same method/code for formatting phone number

For example the format of same Indian mobile number without country code for iOS is different from android SDK

Android SDK: XX XX XXXXXX
iOS SDK: XXXXX XXXXX
While formatting of US phone number using same library in iOS and Android gives similar output but for Indian mobile number the output varies.

http://stackoverflow.com/questions/29773301/why-the-phone-number-format-pattern-is-different-for-the-same-country-on-differe

310 phone numbers with only 7 digits are recognized as valid

310-XXXX phone numbers are found to be valid phone numbers for the state of California. It appears that 310 is actually an area code, and requires an additional 7 digits to be valid.

There are two locations in the metadata .json/.plist files where regexes to match phone numbers end with "|310\d{4}".

EDIT: Was not up to date. Closed.

Crash due to appending a nil string

Looks like the lib is crashing when appending a nil string.
The issue seems to be if the mapping has no entry for the found string.
normalizedChar = [[self.phoneUtil_ DIGIT_MAPPINGS] objectForKey:nextChar];
: @"");
[self.accruedInputWithoutFormatting_ appendString:normalizedChar];

I suggest passing an empty string or not appending at all.
normalizedChar = [[self.phoneUtil_ DIGIT_MAPPINGS] objectForKey:nextChar];
normalizedChar = (normalizedChar && normalizedChar.length>0 ? normalizedChar : @"");
[self.accruedInputWithoutFormatting_ appendString:normalizedChar];

Application Specific Information:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString appendString:]: nil argument'

Last Exception Backtrace:
0 CoreFoundation 0x2e263e8b exceptionPreprocess + 131
1 libobjc.A.dylib 0x3855d6c7 objc_exception_throw + 36
2 CoreFoundation 0x2e263dcd +[NSException raise:format:] + 110
3 CoreFoundation 0x2e2285e7 mutateError + 156
4 0x00209c71 -NBAsYouTypeFormatter normalizeAndAccrueDigitsAndPlusSign_:rememberPosition:
5 0x00207dad -NBAsYouTypeFormatter inputDigitWithOptionToRememberPosition_:rememberPosition:
6 0x00207c5b -NBAsYouTypeFormatter inputDigit:
7 0x000dde1b -BLPhoneViewController textField:shouldChangeCharactersInRange:replacementString:
8 0x0013058d -A2DynamicUITextFieldDelegate textField:shouldChangeCharactersInRange:replacementString:
9 UIKit 0x30f8b1d5 -[UITextField fieldEditor:shouldInsertText:replacingRange:] + 90
10 UIKit 0x30ca4041 -[UIFieldEditor textInput:shouldChangeCharactersInRange:replacementText:] + 46
11 UIKit 0x30f8fd3b -[UITextInputController _delegateShouldChangeTextInRange:replacementText:] + 96
12 UIKit 0x30f954ed -[UITextInputController paste:] + 734
13 UIKit 0x30dbef89 -[UICalloutBar buttonPressed:] + 306
14 Foundation 0x2ec3e4cf __NSFireDelayedPerform + 412
15 CoreFoundation 0x2e22ee87 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION
+ 12
16 CoreFoundation 0x2e22eaa3 __CFRunLoopDoTimer + 792
17 CoreFoundation 0x2e22ce2b __CFRunLoopRun + 1216
18 CoreFoundation 0x2e197541 CFRunLoopRunSpecific + 522
19 CoreFoundation 0x2e197323 CFRunLoopRunInMode + 104
20 GraphicsServices 0x32ece2eb GSEventRunModal + 136
21 UIKit 0x30a4e1e5 UIApplicationMain + 1134
22 0x000e7173 main (main.m:17)
23 libdyld.dylib 0x38a56ab7 start + 0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.