PhoneNumberKit

repository·master·Indexed 26 days ago

https://github.com/marmelroy/phonenumberkit

A Swift framework for parsing, formatting, and validating international phone numbers, inspired by Google's libphonenumber. It provides core utility logic via PhoneNumberUtility and UI components such as PhoneNumberTextField for iOS. Note: The marmelroy/phonenumberkit repository is frozen at version 4.3.0; active development has moved to the PhoneNumberKit organization (version 5.0.0+).

Tokens
2.2K
Snippets
7
Records
11
Agent score
90%

What's inside PhoneNumberKit

  1. Migrate from PhoneNumberKit 0.x to 1.0

    master

    The 1.0 release introduces breaking changes to align with Swift 3.0 API standards. The primary change is the introduction of the PhoneNumberKit object as the central coordinator for parsing and formatting, replacing the previous pattern of using a PhoneNumber object directly for these tasks.

    Key changes:

    • Centralized Object: Use a PhoneNumberKit instance to perform parsing and formatting.
    • Lifecycle Management: PhoneNumberKit objects are relatively expensive to allocate; you should create one instance and reuse it throughout your application lifecycle.
    • Strong Validation: In 1.0, type validation is performed during the parsing process. All PhoneNumber objects are now strongly validated by default, whereas 0.x used computed properties that provided 'light' validation.
  2. Install PhoneNumberKit via Swift Package Manager

    master

    Swift Package Manager is the preferred method for installation.

    Via Xcode UI:

    1. Select File > Swift Packages > Add Package Dependency.
    2. Enter https://github.com/marmelroy/PhoneNumberKit.git.
    3. Set the version resolving rule to Up to Next Major from 4.0.0.
    4. Add the PhoneNumberKit library to your app target.

    Via Package.swift:

    dependencies: [
        .package(url: "https://github.com/marmelroy/PhoneNumberKit", from: "4.0.0")
    ]
  3. Update PhoneNumberKit metadata manually

    master

    PhoneNumberKit uses metadata from Google's libphonenumber. While updating the library to the latest release is usually sufficient, you can manually update the metadata by replacing the XML source and running the update script.

    Prerequisites: You must have the xmljson Python library installed:

    pip install xmljson

    Steps to update:

    1. Download a newer version of the XML metadata file from the libPhoneNumber resources.
    2. Replace the existing XML file in your PhoneNumberKit project with the downloaded file.
    3. Run the update script from your terminal:
    ./update.sh
  4. Migrate to the new PhoneNumberKit organization

    master

    ⚠️ Note: This repository is frozen at version 4.3.0 and is no longer maintained.

    Active development has moved to the PhoneNumberKit organization. To ensure your application uses up-to-date metadata and receives updates, you should migrate:

    • Core (parsing/formatting/validation): Use https://github.com/PhoneNumberKit/PhoneNumberKit (version 5.0.0+). The module name PhoneNumberKit remains unchanged, so core usage requires no source changes.
    • UI (PhoneNumberTextField, country-code picker): Add the PhoneNumberKitUI package and import PhoneNumberKitUI.
  5. Use PhoneNumberKit for parsing and formatting in 1.0

    master

    In PhoneNumberKit 1.0, you must instantiate a PhoneNumberKit object to parse number strings and format PhoneNumber values. The parse method is used to convert a string into a PhoneNumber, and the format method is used to convert a PhoneNumber into a formatted string using a specific toType (e.g., .international).

    let phoneNumberKit = PhoneNumberKit()
    do {
        let phoneNumber = try phoneNumberKit.parse("+44 20 7031 3000", withRegion: "GB")
        let formattedNumber: String = phoneNumberKit.format(phoneNumber, toType: .international)
    }
    catch {
        print("Generic parser error")
    }
  6. Customize the Country Picker UI

    master

    You can customize the appearance of the Country Picker View Controller by configuring CountryCodePickerOptions and assigning it to the textField.withDefaultPickerUIOptions property.

    Options include:

    • backgroundColor / backgroundColorSelection
    • separatorColor
    • tintColor
    • cellOptions: Controls textLabelColor, textLabelFont, detailTextLabelColor, detailTextLabelFont, backgroundColor, and cellType (e.g., .cellNib).
    • headerOptions: Controls textLabelColor, textLabelFont, backgroundColor, cellType, and height.
    let headerOptions = CountryCodePickerOptions.CountryCodePickerHeaderOptions(
        textLabelColor: .blue,
        textLabelFont: .boldSystemFont(ofSize: 18),
        backgroundColor: nil,
        cellType: .cellNib(headerNib, identifier: CustomHeaderView.reuseIdentifier),
        height: CustomHeaderView.defaultHeight
    )
    
    let cellOptions = CountryCodePickerOptions.CountryCodePickerCellOptions(
        textLabelColor: nil,
        textLabelFont: nil,
        detailTextLabelColor: nil,
        detailTextLabelFont: nil,
        backgroundColor: nil,
        backgroundColorSelection: nil,
        cellType: .cellNib(cellNib, identifier: CustomCell.reuseIdentifier),
        height: CustomCell.defaultHeight
    )
    
    let options = CountryCodePickerOptions(
        backgroundColor: .systemGroupedBackground,
        separatorColor: .opaqueSeparator,
        tintColor: UIView().tintColor,
        cellOptions: cellOptions,
        headerOptions: headerOptions
    )
    
    textField.withDefaultPickerUIOptions = options
  7. Use PhoneNumberUtility for parsing and formatting

    master

    All interactions with the library occur through a PhoneNumberUtility instance.

    Important: PhoneNumberUtility is relatively expensive to allocate because it parses metadata into memory. You should allocate it once and reuse it throughout the lifecycle of your application.

    Parsing a single number

    Use .parse() to convert a string into a PhoneNumber object. You can optionally provide a withRegion and set ignoreType: true to skip costly hard type validation.

    Parsing an array of numbers

    For high-performance batch parsing, use the array-based .parse() method. Invalid numbers are automatically ignored in the resulting array.

    Formatting

    Format PhoneNumber objects using .format(_:toType:) with types like .e164, .international, or .national.

  8. Access raw metadata via PhoneNumberUtility

    master

    For advanced customization, you can access the underlying metadata directly. This allows you to program custom behaviors based on the library's data.

    Example: Accessing an example mobile number for Australia (AU) via metadata.

    phoneNumberUtility.metadata(for: "AU")?.mobile?.exampleNumber // 412345678
  9. Use PhoneNumberTextField for AsYouType formatting

    master

    Replace your standard UITextField with PhoneNumberTextField to enable automatic formatting as the user types. If using Interface Builder, ensure the module field is set to PhoneNumberKit.

    Customization

    • withFlag: Displays the country code flag for the currentRegion in the leftView.
    • withExamplePlaceholder: Uses an attributed placeholder to show an example number for the currentRegion.
    • withPrefix: Automatically inserts the country code's prefix and removes it when editing changes.

    To override the default region, subclass PhoneNumberTextField:

    class MyGBTextField: PhoneNumberTextField {
        override var defaultRegion: String {
            get { return "GB" }
            set {}
        }
    }
    class MyGBTextField: PhoneNumberTextField {
        override var defaultRegion: String {
            get {
                return "GB"
            }
            set {} // exists for backward compatibility
        }
    }