Skip to content

Instantly share code, notes, and snippets.

@benaubin
Created January 8, 2018 21:47
Show Gist options
  • Save benaubin/53822f9be91b90474bda884765ddad24 to your computer and use it in GitHub Desktop.
Save benaubin/53822f9be91b90474bda884765ddad24 to your computer and use it in GitHub Desktop.
Using PhoneNumberKit to... format phone numbers
import Foundation
import Cocoa
import PhoneNumberKit
@objc
class PhoneNumberFormatter: Formatter {
static private let phoneNumberKit = PhoneNumberKit()
static private let partialPhoneNumberFormatter = PartialFormatter()
public var enabled = true
override func string(for obj: Any?) -> String? {
guard let str = obj as? String else { return nil }
if(enabled){
guard let phoneNumber = try? PhoneNumberFormatter.phoneNumberKit.parse(str) else {
return nil
}
return PhoneNumberFormatter.phoneNumberKit.format(phoneNumber, toType: .international)
} else {
return str
}
}
override func getObjectValue(_ obj: AutoreleasingUnsafeMutablePointer<AnyObject?>?, for string: String, errorDescription errorStr: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {
if(enabled){
do {
let phoneNumber = try PhoneNumberFormatter.phoneNumberKit.parse(string)
obj?.pointee = PhoneNumberFormatter.phoneNumberKit.format(phoneNumber, toType: .e164) as AnyObject
return true
} catch {
errorStr?.pointee = error.localizedDescription as NSString
return false
}
} else {
obj?.pointee = string as AnyObject
return true
}
}
override func isPartialStringValid(_ partialString: String, newEditingString newString: AutoreleasingUnsafeMutablePointer<NSString?>?, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {
if(enabled){
let formatted = PhoneNumberFormatter.partialPhoneNumberFormatter.formatPartial(partialString)
newString?.pointee = formatted as NSString
return partialString == formatted
} else {
return true
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment