使用 Swift 呼叫 phone 号码

Calling a phone number with Swift

如何将存储 phone 号码的变量分配给按钮以呼叫该号码?

我正在使用 Swift。这是我的代码:

func base() {

    var myBase = sharedDefaults!.objectForKey("base") as? String

    if myBase != nil {
        if myBase == "FRA" {
            titleLabel.text = "FRANKFURT"
            adressLabel.text = "some adress"
            var phone = "+49123456 69 69804616"
            coorPhone.setTitle("Duty Desk : \(phone)", forState: .Normal)
            logoImage.image = UIImage(named: "flaggermany")

        } else if myBase == "LHR" {
            titleLabel.text = "LONDON"
            adressLabel.text = "some adress"
            var phone = "+44123456"

            coorPhone.setTitle("Duty Desk : \(phone)", forState: .Normal)

            logoImage.image = UIImage(named: "flaguk")

        }
    }

    @IBAction func phoneButtonPressed(sender: AnyObject) {
        // let telUrlString = "tel://" + phone
        // UIApplication.sharedApplication().openURL(NSURL(string: "\      (telUrlString)")!)
    }
@IBAction func phoneButtonPressed(sender: UIButton) {
    if let url = NSURL(string: "tel://\(phone)") {
        UIApplication.sharedApplication().openURL(url)
    }
}

如果您在 viewController.swift 文件的顶部(在 class 调用下方)定义变量 phone,则可以使用此代码,这样就可以在函数。

您可以将 phone 变量声明为 class 的全局变量,方法是在 class 声明的下方声明它,如下所示:

class ViewController: UIViewController {

     let sharedDefaults = NSUserDefaults.standardUserDefaults()
     var phone = ""

}

通过这种方式声明,您可以在 class 中的任何位置访问它,现在您可以在函数中以这种方式为其赋值:

func base() {

    var myBase = sharedDefaults.objectForKey("base") as? String

    if myBase != nil {
        if myBase == "FRA" {

            titleLabel.text = "FRANKFURT"
            adressLabel.text = "some adress"
            phone = "+49123456 69 69804616"
            coorPhone.setTitle("Duty Desk : \(phone)", forState: .Normal)
            logoImage.image = UIImage(named: "flaggermany")


        }
        else if myBase == "LHR" {
            titleLabel.text = "LONDON"
            adressLabel.text = "some adress"
            phone = "+44123456"
            coorPhone.setTitle("Duty Desk : \(phone)", forState: .Normal)
            logoImage.image = UIImage(named: "flaguk")

        }
    }
}

之后你可以这样在另一个函数中使用它:

@IBAction func phoneButtonPressed(sender: AnyObject) {

    if let url = NSURL(string: "tel://\(phone)") {
        UIApplication.sharedApplication().openURL(url)
    }
}

希望对您有所帮助。