libPhoneNumber-iOS
iOS port from libphonenumber (Google's phone number handling library)
Top Related Projects
Google's common Java, C++ and JavaScript library for parsing, formatting, and validating international phone numbers.
A Swift framework for parsing, formatting and validating international phone numbers. Inspired by Google's libphonenumber.
Generate Java types from JSON or JSON Schema and annotate those types for data-binding with Jackson, Gson, etc
PHP version of Google's phone number handling library
Quick Overview
libPhoneNumber-iOS is a port of Google's libphonenumber library for iOS. It provides functionality for parsing, formatting, and validating international phone numbers. This library is essential for developers working with phone numbers in iOS applications, offering a robust solution for handling various phone number formats across different countries.
Pros
- Comprehensive phone number handling for multiple countries
- Regular updates to keep pace with changing phone number formats
- Well-documented and easy to integrate into iOS projects
- Supports both Objective-C and Swift
Cons
- Large library size may increase app bundle size
- Occasional discrepancies with the original Google libphonenumber library
- May require frequent updates to stay current with phone number changes
- Performance can be slower for bulk operations
Code Examples
- Parsing a phone number:
let phoneUtil = NBPhoneNumberUtil()
do {
let phoneNumber = try phoneUtil.parse("+1 650 253 0000", defaultRegion: "US")
print(phoneNumber)
} catch {
print("Error parsing number: \(error)")
}
- Formatting a phone number:
let phoneUtil = NBPhoneNumberUtil()
do {
let phoneNumber = try phoneUtil.parse("+1 650 253 0000", defaultRegion: "US")
let formattedNumber = try phoneUtil.format(phoneNumber, numberFormat: .INTERNATIONAL)
print(formattedNumber) // Output: +1 650-253-0000
} catch {
print("Error formatting number: \(error)")
}
- Validating a phone number:
let phoneUtil = NBPhoneNumberUtil()
do {
let phoneNumber = try phoneUtil.parse("+1 650 253 0000", defaultRegion: "US")
let isValid = phoneUtil.isValidNumber(phoneNumber)
print("Is valid: \(isValid)") // Output: Is valid: true
} catch {
print("Error validating number: \(error)")
}
Getting Started
- Add the library to your project using CocoaPods:
pod 'libPhoneNumber-iOS', '~> 0.9'
- Import the library in your Swift file:
import libPhoneNumber
- Create an instance of
NBPhoneNumberUtiland start using the library:
let phoneUtil = NBPhoneNumberUtil()
// Use phoneUtil to parse, format, or validate phone numbers
Competitor Comparisons
Google's common Java, C++ and JavaScript library for parsing, formatting, and validating international phone numbers.
Pros of libphonenumber
- More comprehensive and widely used, with support for multiple programming languages
- Regularly updated with the latest phone number formats and metadata
- Extensive documentation and community support
Cons of libphonenumber
- Larger library size, which may impact app size and performance
- More complex setup and integration process for iOS projects
- Requires additional steps to use in Swift projects
Code Comparison
libPhoneNumber-iOS:
let phoneUtil = NBPhoneNumberUtil()
let phoneNumber = try phoneUtil.parse("+1 650 253 0000", defaultRegion: "US")
let isValid = phoneUtil.isValidNumber(phoneNumber)
libphonenumber:
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
PhoneNumber phoneNumber = phoneUtil.parse("+1 650 253 0000", "US");
boolean isValid = phoneUtil.isValidNumber(phoneNumber);
Key Differences
- libPhoneNumber-iOS is specifically designed for iOS development, while libphonenumber is a more general-purpose library
- libPhoneNumber-iOS offers a more native Swift/Objective-C experience
- libphonenumber provides broader language support and more frequent updates
Recommendation
Choose libPhoneNumber-iOS for iOS-specific projects that prioritize ease of integration and a native feel. Opt for libphonenumber if you need cross-platform support or require the most up-to-date phone number data and formats.
A Swift framework for parsing, formatting and validating international phone numbers. Inspired by Google's libphonenumber.
Pros of PhoneNumberKit
- Written in Swift, providing better integration with modern iOS projects
- Lightweight and has fewer dependencies
- Offers a more Swifty API with better use of optionals and error handling
Cons of PhoneNumberKit
- May have less comprehensive coverage of edge cases compared to libPhoneNumber-iOS
- Potentially slower parsing performance for large datasets
- Less frequent updates and maintenance
Code Comparison
libPhoneNumber-iOS:
NBPhoneNumberUtil *phoneUtil = [[NBPhoneNumberUtil alloc] init];
NSError *anError = nil;
NBPhoneNumber *myNumber = [phoneUtil parse:@"6012345678"
defaultRegion:@"MY" error:&anError];
PhoneNumberKit:
let phoneNumberKit = PhoneNumberKit()
do {
let phoneNumber = try phoneNumberKit.parse("6012345678", withRegion: "MY")
} catch {
print("Parsing error: \(error)")
}
Both libraries provide similar functionality for parsing phone numbers, but PhoneNumberKit offers a more Swift-friendly syntax with better error handling through the use of do-try-catch blocks. libPhoneNumber-iOS, being Objective-C based, uses the traditional NSError pattern for error handling.
Generate Java types from JSON or JSON Schema and annotate those types for data-binding with Jackson, Gson, etc
Pros of jsonschema2pojo
- Generates Java POJOs from JSON Schema, making it easier to work with JSON data in Java applications
- Supports customization of generated code through annotations and configuration options
- Can be integrated into build processes (Maven, Gradle) for automated code generation
Cons of jsonschema2pojo
- Limited to Java language, while libPhoneNumber-iOS is specifically for iOS development
- Requires additional setup and configuration compared to the more focused functionality of libPhoneNumber-iOS
- May generate unnecessary code for simple JSON structures, potentially increasing project complexity
Code Comparison
jsonschema2pojo:
@JsonProperty("phoneNumber")
private String phoneNumber;
public String getPhoneNumber() {
return phoneNumber;
}
libPhoneNumber-iOS:
let phoneUtil = NBPhoneNumberUtil()
let phoneNumber = try phoneUtil.parse("+1 650 253 0000", defaultRegion: "US")
let formattedNumber = try phoneUtil.format(phoneNumber, numberFormat: .NATIONAL)
While jsonschema2pojo generates Java classes for working with JSON data, libPhoneNumber-iOS provides specific functionality for parsing and formatting phone numbers in iOS applications. The code examples demonstrate the different focus areas of these libraries, with jsonschema2pojo handling JSON property mapping and libPhoneNumber-iOS dealing with phone number operations.
PHP version of Google's phone number handling library
Pros of libphonenumber-for-php
- Written in PHP, making it easier to integrate with PHP-based projects
- More actively maintained with frequent updates and contributions
- Larger community support and more comprehensive documentation
Cons of libphonenumber-for-php
- Not optimized for mobile platforms, potentially less efficient for iOS applications
- Requires PHP runtime, which may not be ideal for iOS development environments
- May have a larger footprint compared to native iOS libraries
Code Comparison
libphonenumber-for-php:
$phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
$phoneNumber = $phoneUtil->parse("+1 202-456-1414", "US");
$isValid = $phoneUtil->isValidNumber($phoneNumber);
libPhoneNumber-iOS:
let phoneUtil = NBPhoneNumberUtil()
let phoneNumber = try phoneUtil.parse("+1 202-456-1414", defaultRegion: "US")
let isValid = phoneUtil.isValidNumber(phoneNumber)
Both libraries offer similar functionality for parsing and validating phone numbers. The main difference lies in the language and ecosystem they're designed for. libphonenumber-for-php is better suited for PHP-based web applications, while libPhoneNumber-iOS is tailored for iOS app development. The choice between them depends on the specific project requirements and development environment.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
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 (zen.isis@gmail.com)
Updating libPhoneNumber MetaData
We are dependent on the community to help keep this library up-to-date with the latest libPhoneNumber MetaData from Google.
When new versions of libPhoneNumber MetaData are released from Google, please feel free to work to update this repo with a pull request. Make sure to follow the steps below to update the main MetaData & the Geocoding MetaData (even if you don't consume all of the functionality).
To see the current version of MetaData used by this library, check the commit comments and/or release notes. To correlate the version of metadata go to Google's libphonenumber repo.
Update Main MetaData
-
cdinto thescriptsdirectory -
Run
metadataGenerator.swiftpassing in the desired version number./metadataGenerator.swift 1.2.3 -
Run
GeneratePhoneNumberMetaDataFiles.shto update the generated files -
Update the
generatedJSONfiles to be "pretty printed" so that consumers can easily compare commits to see differences (add the-pargument)./metadataGenerator.swift 1.2.3 -p
NOTE: Don't want to generate the phone number MetaData off of the pretty-printed files because that takes up A LOT more space
Update Geocoding MetaData
- Open the libPhoneNumber-GeocodingParser project in Xcode
- Edit the libPhoneNumber-GeocodingParser Scheme
- In the
Runsection go to theArgumentstab - Edit the version argument to be the desired version number
- Add an argument specifying the output directory (ex.
/Users/john.doe/geocoding) - Run the libPhoneNumber-GeocodingParser program in Xcode (
Cmd+R) on your machine - Wait a few minutes for the program to complete (the console will say when the program is done)
- Copy the
*.dbfiles from your specified output directory tolibPhoneNumberGeocodingMetaData/GeocodingMetaData.bundle
Validating Updates
- Open the libPhoneNumber project in Xcode
- Run the tests for each library of the project:
- libPhoneNumber
- libPhoneNumberGeocoding
- libPhoneNumberShortNumber
- Open the
Package.swiftSPM project in Xcode - Run the tests for the package -
libPhoneNumber-Package(runs the tests for each of the package targets in one run)
Optional Validation: Cocoapods
cdinto thelibPhoneNumber-Demodirectory- Verify the
Podfileis pointing to the local copies of the pods (using:path => '../') - Run
pod install - Open the
libPhoneNumber-Demoproject in Xcode - Run the demo project validating phonenumber formatting works as expected
Optional Validation: Swift Package Manager
- Open the
libPhoneNumber-Demo-SPMproject in Xcode - Verify the
libPhoneNumberpackage is using thelocalversion - Run the demo project validating phonenumber formatting works as expected
- Change the
libPhoneNumberto use theremoteversion (will need to point at the branch) - Build the demo project validating everything builds successfully
- Can also run the demo, but validating successful build will probably provide all the necessary value
Creating A New Version
- Determine what the next version should be based on whether the release is:
- JUST Bug fixes - increase the 3rd digit - 1.2.0 --> 1.2.1
- Updated Metadata or added functionality - increase the "minor version" - 1.1.0 --> 1.2.0
- Major changes, possibly non-passive - increase the "major version" - 1.5.0 --> 2.0.0
- Use the script (in the
scriptsfolder) -versionCommitter.swift.
Pass the new version into the script and push it to the proper remote repo to create a pull request
scripts/versionCommitter.swift 2.2.4 --push --remote myOrigin
3. Lint the cocoapod
pod lib lint libPhoneNumber-iOS.podspec
4. Create a pull request for the created branch (ex: Version-2.2.4)
5. Create a draft release in github describing the changes
6. Try to get at least 2 approvals on the pull request
7. Pull in pull request onto master
8. Push the podspec
pod trunk push libPhoneNumber-iOS.podspec
Top Related Projects
Google's common Java, C++ and JavaScript library for parsing, formatting, and validating international phone numbers.
A Swift framework for parsing, formatting and validating international phone numbers. Inspired by Google's libphonenumber.
Generate Java types from JSON or JSON Schema and annotate those types for data-binding with Jackson, Gson, etc
PHP version of Google's phone number handling library
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot