Search code examples
swiftios11xcode10

converting String Type to phoneNumber


I have a string that is actually a phone number. This string is stored as variable PhoneNumber in my database.

I want to convert this to a type phoneNumber() and then format it using the PhoneNumberKit and then put it back into a label as a string How should i do this?

Convert the string to integer and then convert the string to phoneNumber struct present in phone number kit?

or is there anyway of simply passing the string itself to format function in phone Numberkit?

I have not written a full code yet. So this is what i have in my code:

    func formatTOPhoneNumber(){
    // userNumber is the string that is phone number
    var userNumber = User.shared.phoneNumber 
    var num = (userNumber! as NSString).integerValue

    }

Solution

  • The PhoneNumberKit library works with strings. Use the parse method to convert it into a PhoneNumber object. Then use the format function to convert it into a string:

    var formattedString = ""
    do {
      let phoneNumberKit = PhoneNumberKit()
      let phoneNumber = try phoneNumberKit.parse(userNumber)
    
      formattedString = phoneNumberKit.format(phoneNumber, toType: .e164)
    }
    catch {
      print("Generic parser error")
    }
    

    Try reading the documentation before asking a question, you might attract some downvotes when you haven't done any prior research.