确保电话号码UITextField带有“ +”前缀

时间:2019-05-24 16:45:52

标签: swift xcode uitextfield phone-number

我有几个UITextField,用户可以在其中插入电话号码。当我单击发送按钮时,它会自动向列出的号码发送消息。一切正常,但是我想做的是,当我单击“发送”按钮时,我希望它检查其中包含文本的UITextFields是否在电话号码前面带有+符号在与我的服务器连接以发送自动消息之前列出。如果列出的电话号码没有+符号,我该如何向用户发送警报?

ViewController:

class ViewController: UIViewController {

   @IBOutlet weak var scrollviewcontact: UIScrollView!
    @IBOutlet weak var viewcontact: UIView!

    @IBOutlet weak var phonenumber: UITextField!
    @IBOutlet weak var phonenumber1: UITextField!
    @IBOutlet weak var phonenumber2: UITextField!
    @IBOutlet weak var phonenumber3: UITextField!

    var currentTextField: UITextField?

    private let contactPicker = CNContactPickerViewController()

    override func viewDidLoad() {
        super.viewDidLoad()

        phonenumber.textContentType = .telephoneNumber
        phonenumber1.textContentType = .telephoneNumber
        phonenumber2.textContentType = .telephoneNumber
        phonenumber3.textContentType = .telephoneNumber

     }


    @IBAction func sendbutton(_ sender: Any) {

        var numArray: Array<Any>

        numArray = [phonenumber.text!, phonenumber1.text!, phonenumber2.text!, phonenumber3.text!]

            let Url = String(format: "//URL")
            guard let serviceUrl = URL(string: Url) else { return }
            var request = URLRequest(url: serviceUrl)
            request.httpMethod = "POST"
            request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
            guard let httpBody = try? JSONSerialization.data(withJSONObject: numArray, options:[]) else {
                return
            }
            request.httpBody = httpBody

            let session = URLSession.shared
            session.dataTask(with: request) { (data, response, error) in
                if let response = response {
                    print(response)
                }
                if let data = data {
                    do {
                        let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments)
                        print("json ", json)
                    } catch {
                        print(error)
                    }
                }
                }.resume()



}
    extension ViewController: CNContactPickerDelegate {

        func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {


            let phoneNumberCount = contact.phoneNumbers.count

            guard phoneNumberCount > 0 else {
                dismiss(animated: true)

                return
            }

            if phoneNumberCount == 1 {
                setNumberFromContact(contactNumber: contact.phoneNumbers[0].value.stringValue)

            }else{

                let alertController = UIAlertController(title: "Select one of the numbers", message: nil, preferredStyle: .alert)

                for i in 0...phoneNumberCount-1 {
                    let phoneAction = UIAlertAction(title: contact.phoneNumbers[i].value.stringValue, style: .default, handler: {
                        alert -> Void in
                        self.setNumberFromContact(contactNumber: contact.phoneNumbers[i].value.stringValue)
                    })
                    alertController.addAction(phoneAction)
                }
                let cancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: {
                    alert -> Void in

                })
                alertController.addAction(cancelAction)

                dismiss(animated: true)
                self.present(alertController, animated: true, completion: nil)
            }
        }

        func setNumberFromContact(contactNumber: String) {

            var contactNumber = contactNumber.replacingOccurrences(of: "-", with: "")
            contactNumber = contactNumber.replacingOccurrences(of: "(", with: "")
            contactNumber = contactNumber.replacingOccurrences(of: ")", with: "")
            contactNumber = contactNumber.replacingOccurrences(of: " ", with: "")

            currentTextField?.text = String(contactNumber)

        }

        func contactPickerDidCancel(_ picker: CNContactPickerViewController) {

        }
}

我要实现的目标是,单击“发送按钮”时,它将检查哪个UITextField中包含文本,以及是否没有+作为前缀,则会弹出一条警告消息。

2 个答案:

答案 0 :(得分:0)

您可以尝试

let numArray = [phonenumber.text!, phonenumber1.text!, phonenumber2.text!, phonenumber3.text!] 
guard numArray.filter { $0.hasPrefix("+") }.count == numArray.count else { 
  // alert with message make sure all textfields has + prefix
 return
}

答案 1 :(得分:0)

您可以使用hasPrefix方法。例如:

for num in numArray {
    if num.hasPrefix("+") {
        // do something
    } else {
        // do something else
    }
}