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