Search code examples
iosobjective-ciphoneswiftcall

click on a label in Swift


I want to make the label that on click on it to make call to number. I know that iOS has this option, but how can I do it in Swift?

I found just how to do it in ObjC:

-(IBAction)callPhone:(id)sender {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel:2135554321"]];
}

Can anyone help me with it?


Solution

  • UIApplication.sharedApplication().openURL(NSURL(string: "tel://2135554321"))
    

    example

    if let  CallURL:NSURL = NSURL(string:"tel://\(yourMobileNUmber)") {
    let application:UIApplication = UIApplication.sharedApplication()
    if (application.canOpenURL( CallURL)) {
      application.openURL( CallURL);
      }
    else
     {
       // your number not valid
       let tapAlert = UIAlertController(title: "Alert!!!", message: "Your mobile number is invalid", preferredStyle: UIAlertControllerStyle.Alert)
    tapAlert.addAction(UIAlertAction(title: "OK", style: .Destructive, handler: nil))
     self.presentViewController(tapAlert, animated: true, completion: nil)
      }
     }
    

    Type-2

      // add gesture to your Label
     var tapGesture = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
     yourLabelName.userInteractionEnabled=true
     yourLabelName.addGestureRecognizer(tapGesture)
    
    // handle the function of UILabel
    func handleTap(sender:UITapGestureRecognizer){
         if let  CallURL:NSURL = NSURL(string:"tel://\(yourMobileNUmber)") {
    let application:UIApplication = UIApplication.sharedApplication()
    if (application.canOpenURL( CallURL)) {
      application.openURL( CallURL);
      }
     else
     {
       // your number not valid
       let tapAlert = UIAlertController(title: "Alert!!!", message: "Your mobile number is invalid", preferredStyle: UIAlertControllerStyle.Alert)
    tapAlert.addAction(UIAlertAction(title: "OK", style: .Destructive, handler: nil))
     self.presentViewController(tapAlert, animated: true, completion: nil)
      }
     }
    }