Skip to content

Instantly share code, notes, and snippets.

@anirudhamahale
Last active April 22, 2021 04:54
Show Gist options
  • Save anirudhamahale/eb8f5322c80e2ef07bb4bdd8c417943b to your computer and use it in GitHub Desktop.
Save anirudhamahale/eb8f5322c80e2ef07bb4bdd8c417943b to your computer and use it in GitHub Desktop.
Returns the country code and phone number from number
```swift
import Foundation
class PhoneNumberManager {
static func readJson() -> [String: Any]? {
if let fileUrl = Bundle.main.url(forResource: "DailerCodeTree", withExtension: "json") {
do {
let data = try Data(contentsOf: fileUrl)
let json = try JSONSerialization.jsonObject(with: data, options: [])
let dictionary = json as! [String: Any]
let plusDictionary = dictionary["+"] as! [String: Any]
return plusDictionary
} catch {
print(error.localizedDescription)
return nil
}
}
print("File not found!")
return nil
}
static func parseCountryCode(_ number: String) -> String? {
var phoneNumber = number
if number.first != "+" {
phoneNumber = "+\(number)"
}
var countryCode = "+"
let phoneDictionary = readJson()!
if phoneNumber.count < 5 {
print("Invalid phone number, phone number should be atleast 5 characters.")
return nil
}
if let firstNumberOfPhone = phoneNumber.getCharacterAt(1) {
countryCode.append(firstNumberOfPhone)
if let firstNumberOfJson = phoneDictionary[firstNumberOfPhone] as? [String: Any] {
if firstNumberOfJson.keys.contains(phoneNumber.getCharacterAt(2)!) {
countryCode.append(phoneNumber.getCharacterAt(2)!)
let secondNumberOfJson = firstNumberOfJson[phoneNumber.getCharacterAt(2)!] as! [String: Any]
if secondNumberOfJson.keys.contains(phoneNumber.getCharacterAt(3)!) {
countryCode.append(phoneNumber.getCharacterAt(3)!)
let thirdNumberOfJson = secondNumberOfJson[phoneNumber.getCharacterAt(3)!] as! [String: Any]
if thirdNumberOfJson.keys.contains(phoneNumber.getCharacterAt(4)!) {
countryCode.append(phoneNumber.getCharacterAt(4)!)
let fourthNumberOfJson = thirdNumberOfJson[phoneNumber.getCharacterAt(4)!] as! [String: Any]
if fourthNumberOfJson.keys.contains(phoneNumber.getCharacterAt(5)!) {
countryCode.append(phoneNumber.getCharacterAt(5)!)
// let fifthNumberOfJson = fourthNumberOfJson[phoneNumber.getCharacterAt(5)!] as! [String: Any]
}
}
}
}
}
}
return countryCode
}
}
```
@anirudhamahale
Copy link
Author

Country code json can be found here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment