marmelroy / phonenumberkit Goto Github PK
View Code? Open in Web Editor NEWA Swift framework for parsing, formatting and validating international phone numbers. Inspired by Google's libphonenumber.
License: MIT License
A Swift framework for parsing, formatting and validating international phone numbers. Inspired by Google's libphonenumber.
License: MIT License
libPhoneNumber has a way to separate a possible phone isPossibleNumber
number from a valid one isValidNumber
:
With PhoneNumberKit, this test fails:
// Invalid brazilian number
func testPossibleButInvalidNumber() {
do {
let phoneNumber = try PhoneNumber(rawNumber: "0765550055", region: "BR")
phoneNumber.toE164()
XCTFail()
}
catch {
XCTAssert(true)
}
}
In PhoneNumberKit a parsed number is a "possible" number correct? Is it possible to dissociate a parsed (possible) number from a valid one? Since this use the same metadata than libPhoneNumber?
We're using PhoneNumberKit internally to check if strings provided by either the user or our APIs are valid phone numbers. We also use it to extract phone number information or to simply format the numbers for display. We think it's awesome, and very much appreciate your work! :)
However, we are having problems defining our very own PhoneNumber
atom; PhoneNumberKit
(the class) causes the Swift compiler to get confused whenever we try to qualify types using the PhoneNumberKit
namespace:
e.g.,
// Note: This code is for illustration purposes only
import PhoneNumberKit
struct PhoneNumber {
let value: String
// ...
var regionCode: String? {
let phoneNumber = try? PhoneNumberKit.PhoneNumber(rawNumber: value)
// ^ Error: Type 'PhoneNumberKit' has no member 'PhoneNumber'
return phoneNumber.flatMap {
PhoneNumberKit.PhoneNumberKit().regionCodeForNumber($0)
// ^ Error: Type 'PhoneNumberKit' has no member 'PhoneNumberKit'
}
}
}
We did some tests where we replaced the PhoneNumberKit import with an import struct PhoneNumberKit.PhoneNumber
on the file in question, and typealiased the PhoneNumberKit
class to a different name (e.g., PhoneNumberManager
) on another file, and it seems like this really is the root of the problem.
We have a few suggestions (all of which, unfortunately, requires some level of API breakage with the current version):
PhoneNumberKit
class: This requires very little changes to both the codebase, and existing users of the library.PhoneNumberKit
into free functions: This aligns with other libraries like Alamofire that exposes free functions, which are then called with their module names, by convention (e.g., Alamofire.request
, etc.).What do you think? We can provide you with a PR if and when you arrive into a conclusion. Thanks!
It would be cool to be able to separate a PhoneNumber's intl prefix from the rest of the phone number, e.g. for a french phone number, "0612345678"
would give the tuple ("+33", "612345678")
This would have multiple applications and possibilities, one of them being to allow the user to select a country in one way, the UI then displaying the selected intl prefix, and let the user enter the rest of the phone number in a TextField then.
PhoneNumberTextField
One UI we want to implement is adding a leftView
to the PhoneNumberTextField
containing an UIButton
. On tap, this will display a UIPickerView
to select the country, and upon selecting one will display e.g. ๐ซ๐ท (+33)
in the button's title.
Then the PhoneNumberTextField
should be able to format the reminder of the phone number taking that fixed country prefix into account
UILabel
In another place in our UI, we need to simply display the phone number, but we may still need to split it for display and layout purposes in two separate labels (e.g. one label in gray text containing the prefix "+33" and another label next to it in black containing the rest)
So this request of being able to split the PhoneNumber is not limited to PhoneNumberTextField
, but should also be made accessible for other purposes and customization as well (maybe make func adjustedNationalNumber()
public instead of private to solve that?)
I'm trying to capture UITextFieldDelegate events, and when I set the delegate in IB, the delegate methods are not called. Same thing happens when I set it in code.
It looks like your set method for the UITextFieldDelegate property continues to set the value to nil. When I performed this fix in my local repo, it solved my issue.
Replace
override public var delegate: UITextFieldDelegate? {
get {
return _delegate
}
set {
self._delegate = delegate
}
}
with
override public var delegate: UITextFieldDelegate? {
get {
return _delegate
}
set {
self._delegate = newValue
}
}
Cheers!
Good job on the Swift 3.0 release ๐ฏ
I've come across an issue with the PhoneNumberTextField. I'm overriding this class to draw a custom border and am receiving the compilation error:
Cannot inherit from non-open class 'PhoneNumberTextField' outside of its defining module
Is it possible to change the access level on the PhoneNumberTextField class to "open" from "public" to facilitate overriding it outside of the module ?
I made a simple textfield to test various phone number inputs.
This # entry 202 00e 0000
returns with a PremiumRate
type and the toE164
string value is +1202003000
It does appear to be taking the alphabetical keypad entry you find on a phone and converting its value. So, would this be a valid entry or should an error return stating it's not a number?
Anyways, just thought I share my findings.
Looks like a great library. Installed with Cocoapods and it's throwing the following error when running the example code from the README: fatal error: unexpectedly found nil while unwrapping an Optional value
do {
let phoneNumber = try PhoneNumber(rawNumber:"+33 6 89 017383")
}
catch {
print("Generic parser error")
}
Installed with cocoapods 0.39 and Xcode 7.1
Hi!
I used you library to format phone numbers entered by user. And though I liked PhoneNumberKit a lot, I discovered certain memory leaks.
Please note that I updated the library to version 0.6.4 via cocoapods, just so you know that I am using the up-to-date version.
It seems both of the following lines cause memory leaks (thus if I delete both of them the leaks go away). Also PhoneNumber (rawNumber:)
was tested in different apps with the same leaks.
do {
_ = try PhoneNumber (rawNumber: phone!)
}
catch {
isValidNumber = false
}
And this one:
let formattedString = PartialFormatter ().formatPartial (cutString)
cutString
is a string starting with +
and ending with numbers.
Below see instruments' screenshots.
When using PhoneNumberKit().parseMultiple()
from time to time I have the following issue:
I didn't really took a look into this more thoroughly, I just want to raise this issue to see if it's already under investigation.
By the way, love this lib! parseMultiple()
is more than 2x more performant than our previous implementation ๐
Will there be a new version to support 3.0 soon?
I'm wondering if you can make this as extension of textfield so that we can easily use another textfield open source for our project?
for example SkyFloatingLabelTextField. so that it is more flexible.
thanks.
When you enter a UK/GB number using the standard way UK citizen will enter the number (with a preceding 0) it is not being parsed correctly as a UK number. Remove the preceding zero and it parses some area codes (mobiles fine), but not others.
Think the issue is that the phone mask for the UK is (0xxxx) 123456 sometimes and (0xxxx) 1234567 at others not (xxxx) 123456 which is never dialled. For international format that would be +44 (xxxx) 123456 or (xxxx) 1234567.
For example:
(0118) 9 345678 (Reading Area Code)
(020) 7 123456 (London Area Code)
(07792) 123456
(01634) 123456 (Kent Area Code)
Entering any of the above fail- in fact, I cannot get a single UK landline number to work. If I exclude the 0 on 7792 123456 that works.
Importance is that 1) Users will definitely enter the number this way and 2) Dialling without the zero will always fail internally to the UK unless the international code replaces it in the position- so you could dial 00441189345678 or 01189345678 and succeed, but dial 1189345678 and it will fail.
Hey Roy!
I have updated to the version 1.0 and got some compile issues associated with PartialFormatter initializers access level (internal). Pls fix it :)
All other stuff work flawlessly - good job!
The method for determining a number's type is incorrect for numbers from a region not the "main country" of a country code. For example:
func testAntiguaPagerNumber() {
guard let number = try? PhoneNumber(rawNumber: "12684061234") else {
XCTFail()
return
}
XCTAssertEqual(number.type, PhoneNumberType.Pager)
}
fails because the type determination uses US metadata instead of AG metadata.
We're using PhoneNumberKit in our app, but are having issues with it correctly identifying extensions. For example the phone number 2129316760 x28
always loses the x28 extension.
(lldb) po phoneNumber
โฟ PhoneNumber
- countryCode : 1
- leadingZero : false
- nationalNumber : 2129316760
- numberExtension : nil
- rawNumber : "12125556760 x28"
We would expect common cases like x28 to be recognized as a valid extension. Additionally, this link which appears to use google's phone number lib parses the phone number correctly.
I see that PhoneNumberTextField is marked open, but the swift 3 compiler is complaining with the error:
Cannot inherit from non-open class 'PhoneNumberTextField' outside of its defining module'
Any ideas?
Great library but it fails to parse some phone numbers (e.g invalid area code, etc). For example, in the iOS simulator the sample Contact Kate Bell has the number (555) 564-8583. I would like to be able to get the E164 format for this number, but parse fails. Could you please provide a way to bypass the area-code validation, so I can still format test phone numbers?
In ParseOperations.swift line 199 now I see "associatedtype" instead of "typealias" which was before, and now it's not compiling anymore. If I do "pod install", project won't run unless I manually change back to typealias.
How to install it manually without cocoapods and etc?
All you have to do is:
$ carthage build --no-skip-current
$ carthage archive PhoneNumberKit
Then just upload the .zip in the project root.
This will save a bunch of time on CI server and the like.
version: 0.8.3
@marmelroy
App won't compile with an error here
Value provider protocol.
*/
public protocol ParseOperationValueProvider {
associatedtype ProvidedInputValueType
}```
halp!!
Hi,
In my app I load the contact list of the user. In this list I want to make non-mobile numbers greyed-out and non-selectable. To do this in the cellForRowAtIndexPath I check the type of the phone number. As I have read and seen in the code this computed value is quite heavy (as it involves quite a lot of regular expressions). This impact can be seen when scrolling through the list.
Is there a way to improve the performance in this scenario? For example is it possible to just check if the number is of .Mobile type, without also determining if it also is of other types (what is currently happening)?
Thanks!
This is the strangest thing. THe only thing I can think of, is that there is a naming conflict, or something. But I've searched the repo, and it doesn't look like that's the case.
I have a static method called create, to help with UIView initialization (I'm laying out all views through code).
extension UIView : Creatable {
}
// can't use 'Self' in extension of NSObject, so have to use a protocol
public protocol Creatable {
init()
}
public extension Creatable where Self: UIView {
static func create(creatorFunc: ((Self)->Void)? = nil) -> Self {
let retval = self.init()
retval.translatesAutoresizingMaskIntoConstraints = false
creatorFunc?(retval)
return retval
}
}
This is for ease of use, so that I can do something like
let fakeView = UITextField.create {
...
}
However, when I import PhoneNumberKit, I'm getting compile-time errors saying that a UITextField no longer has a member 'create'. I'm stumped. When I remove the import line, it compiles correctly again.
Formatting of parsed phone numbers for display is still very basic in 0.1 and should be improved in the next version.
Also, an equivalent to libPhoneNumber's AsYouTypeFormatter would be useful and still within the scope of this framework.
It seems when this is imported, the entire application can no longer use search bars.
Unless there's any reason not to?
My reason for using it would be for a AsYouType TextField I'm putting together until we get PhoneNumberKit's lovely version ๐.
Alternatively, I'd be more than happy to help with implementation/testing with PhoneNumberKit's AsYouType TextField?
Hi,
I am parsing this number +16307792428 and get the type FixedLine when in fact it is a Mobile number.
Google's libphonenumber would return FIXED_LINE_OR_MOBILE.
I am not sure there is a 100% way to detect if it is a mobile or fixed number in this case. Perhaps returning FixedLineOrMobile would be a better option?
I have an issue with PhoneNumberTextField with US region. I want to input some dummy phone number like 12065554444. But when I input the second character the textfield prepend it with one more "1" character - 1 12. Is that correct behavior?
Was getting an empty array back. I used breakpoints to see that the SynchronizedArray.append
async call happens after parseMultiple
returns. I there's a wait missing to wait until SynchronizedArray
's accessQueue
is empty.
Migrating to Swift 3 is resulting in several build time errors including dispatch_once (used in ParseOperation.swift) no longer supported by Swift.
After fixing the above, a runtime error is being encountered while accessing the shared instance of the metadata while running the AsYoutType or Phonebook example apps.
"'NSUnknownKeyException', reason: '[<_SwiftValue 0x60800009f900> valueForUndefinedKey:]: this class is not key value coding-compliant for the key numberFormat."
When I type "+" followed by "9", the "+" sign disappears.
So instead of "+9" , it only shows "9".
It is working fine on my iPhone 5s, iOS 9.3.3 though.
Xcode Version: 7.3
Try running this test loop. You will observe a pretty serious memory leak.
func testMemoryLeak() {
let testNumber = "4081234567"
for var i = 0; i < 100000; i++ {
do {
let phoneNumber = try PhoneNumber(rawNumber: testNumber)
// phoneNumber.toE164()
}
catch {
XCTFail()
}
}
XCTAssert(true)
}
Will you guys be migrating this to Swift 3?
Trying to create a pull request on your project, but I don't have access. Are you open to pull requests?
Hi!
It seems that PhoneNumberKit and BlocksKit are incompatible.
I have set in interface builder a PhoneNumberTextField. It works ok. But I soon as I reactivate my BlocksKit pod, there is a loop with keyboardInputChangedSelection
__invoking___
[A2DynamicDelegate fowrwardInvocation]
And it ultimatly crash with a __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__
Does anyone have this problem?
Thank you
I'm using PhoneNumberKit with carthage and get an iTunes Connect processing error:
"Do not submit apps with GCC-style coverage" for archive submissions.
Is there any way of disabling this warning without manually changing the build "Instrument Program Flow" settings whenever I carthage update or disabling Bitcode in my project?
He,
I'm getting this error when attempting to install the pod. Not sure if there's a way around this โ do you have any suggestions?
[!] The 'Pods' target has transitive dependencies that include static binaries:
I am using Xcode 7.2 Swift 2
Specs satisfying the PhoneNumberKit (~> 0.7)
dependency were found, but they required a higher minimum deployment target.
Any chance you could add a check for the maximum number of characters in PhoneNumberTextField? The input shouldn't allow more than the international format number should be, right?
Really appreciate this plugin btw :)
I recently upgrade to PhoneNumberKit 0.6.4 and xcode gave me this error "Expected Declaration" in ParseOperation.swift
/**
Value provider protocol.
*/
public protocol ParseOperationValueProvider {
associatedtype ProvidedInputValueType
}
Please help.
I am using Carthage. The failures are strange as the build is looking for Alcatraz, which is not supported by Xcode 8. But why would the Kit depends on them.
I also wonder if the current release is compatible with Swift 3.
Thanks!
n build) failed with exit code 65: 2016-09-20 12:03:06.760 xcodebuild[8945:1202269] [MT] PluginLoading: Required plug-in compatibility UUID 8A66E736-A720-4B3C-92F1-33D9962C69DF for plug-in at path '~/Library/Application Support/Developer/Shared/Xcode/Plug-ins/XAlign.xcplugin' not present in DVTPlugInCompatibilityUUIDs 2016-09-20 12:03:06.761 xcodebuild[8945:1202269] [MT] PluginLoading: Required plug-in compatibility UUID 8A66E736-A720-4B3C-92F1-33D9962C69DF for plug-in at path '~/Library/Application Support/Developer/Shared/Xcode/Plug-ins/Swimat.xcplugin' not present in DVTPlugInCompatibilityUUIDs 2016-09-20 12:03:06.762 xcodebuild[8945:1202269] [MT] PluginLoading: Required plug-in compatibility UUID 8A66E736-A720-4B3C-92F1-33D9962C69DF for plug-in at path '~/Library/Application Support/Developer/Shared/Xcode/Plug-ins/RegX.xcplugin' not present in DVTPlugInCompatibilityUUIDs 2016-09-20 12:03:06.762 xcodebuild[8945:1202269] [MT] PluginLoading: Required plug-in compatibility UUID 8A66E736-A720-4B3C-92F1-33D9962C69DF for plug-in at path '~/Library/Application Support/Developer/Shared/Xcode/Plug-ins/OMQuickHelp.xcplugin' not present in DVTPlugInCompatibilityUUIDs 2016-09-20 12:03:06.763 xcodebuild[8945:1202269] [MT] PluginLoading: Required plug-in compatibility UUID 8A66E736-A720-4B3C-92F1-33D9962C69DF for plug-in at path '~/Library/Application Support/Developer/Shared/Xcode/Plug-ins/FuzzyAutocomplete.xcplugin' not present in DVTPlugInCompatibilityUUIDs 2016-09-20 12:03:06.763 xcodebuild[8945:1202269] [MT] PluginLoading: Required plug-in compatibility UUID 8A66E736-A720-4B3C-92F1-33D9962C69DF for plug-in at path '~/Library/Application Support/Developer/Shared/Xcode/Plug-ins/Alcatraz.xcplugin' not present in DVTPlugInCompatibilityUUIDs
These country are missing:
PN : Pitcairn Islands
TF : French Southern Territories
UM : U.S. Outlying Islands
AQ : Antarctica
BV : Bouvet Island
HM : Heard & McDonald Islands
GS : So. Georgia & So. Sandwich Isl.
Added source files manually, but see error log:
dyld: Library not loaded: @rpath/PhoneNumberKit.framework/PhoneNumberKit
Referenced from: /var/mobile/Containers/Bundle/Application/BB4879D5-ADAA-4B1A-9D2C-2318D7B78DCA/App.app/App
Reason: image not found
Code example:
let numberPhone = try PhoneNumber(rawNumber: "(636) 275-4512")
let countryCodeNumber = numberPhone.countryCode
let phoneNumberKit = PhoneNumberKit()
var countryCode = phoneNumberKit.countriesForCode(countryCodeNumber)?.first
log:
countryCodeNumber = 1
countryCode = "AG" // Should be US
Do you think it's possible to update your module for 0 alloc and 0 copy ?
It's most likely something I'm missing or not understanding, but I replaced the UITextField with PhoneNumberTextField in both my code at my IBOutlet and in the Storyboard but it does not seem to actually formate as I type, is there something that I might be missing?
Hey Roy,
Firstly thank you for this nice library.
I look for the phone number template from region to show it in the placeholder of the text field
Do you know how we can do that ?
Example from Google PhoneNumber API :
// Produces "011 41 44 668 1800", the number when it is dialed in the United States.
System.out.println(phoneUtil.formatOutOfCountryCallingNumber(swissNumberProto, "US"));
Thank you for your help
Hamza
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.