birkyboy
birkyboy

Reputation: 61

Calling a phone number with Swift

How can I assign a variable that stores a phone number to a button to call that number?

I am using Swift. Here is my code:

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)")!)
    }

Upvotes: 1

Views: 5244

Answers (2)

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71862

You can declare your phone variable as a global for your class by declaring it at the below of your class declaration as shown below:

class ViewController: UIViewController {

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

}

By declaring this way you can access it anywhere in your class and now you can assign value to it this way in your function:

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")

        }
    }
}

After that you can use it this way into another function:

@IBAction func phoneButtonPressed(sender: AnyObject) {

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

Hope this will help you.

Upvotes: 2

Charlie Hall
Charlie Hall

Reputation: 577

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

you can use this code if you define the variable phone at the top of your viewController.swift file (below the class call), that way it can be accessed in the function.

Upvotes: 2

Related Questions