Llamar al número de teléfono de swift


Estoy tratando de llamar a un número no utilizando números específicos, sino un número que se llama en una variable o al menos decirle que tire hacia arriba el número en su teléfono. Este número que se llama en una variable es un número que he recuperado mediante el uso de un analizador sintáctico o agarrar de un sitio web sql. Hice un botón tratando de llamar al número de teléfono almacenado en la variable con una función, pero fue en vano. Cualquier cosa ayudará gracias!

    func callSellerPressed (sender: UIButton!){
 //(This is calls a specific number)UIApplication.sharedApplication().openURL(NSURL(string: "tel://######")!)

 // This is the code I'm using but its not working      
 UIApplication.sharedApplication().openURL(NSURL(scheme: NSString(), host: "tel://", path: busPhone)!)

        }
Author: Vadim Kotov, 2014-12-03

17 answers

Solo inténtalo:

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

Suponiendo que el número de teléfono está en busPhone.

NSURL's init(string:) devuelve un Opcional, por lo que al usar if let nos aseguramos de que url es un NSURL (y no un NSURL? como lo devuelve init).


Para Swift 3:

if let url = URL(string: "tel://\(busPhone)"), UIApplication.shared.canOpenURL(url) {
    if #available(iOS 10, *) {
        UIApplication.shared.open(url)
    } else {
        UIApplication.shared.openURL(url)
    }
}

Tenemos que comprobar si estamos en iOS 10 o posterior porque:

'openURL' fue obsoleto en iOS 10.0

 139
Author: Thomas Müller,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-08 23:53:31

Una solución autónoma en iOS 10, Swift 3 :

private func callNumber(phoneNumber:String) {

  if let phoneCallURL = URL(string: "tel://\(phoneNumber)") {

    let application:UIApplication = UIApplication.shared
    if (application.canOpenURL(phoneCallURL)) {
        application.open(phoneCallURL, options: [:], completionHandler: nil)
    }
  }
}

Debería poder usar callNumber("7178881234") para hacer una llamada.

 55
Author: Zorayr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-17 20:10:06

Bien, conseguí ayuda y lo resolví. También puse un pequeño sistema de alerta en caso de que el número de teléfono no sea válido. Mi problema era que lo estaba llamando bien, pero el número tenía espacios y caracteres no deseados como ("123 456-7890"). UIApplication solo funciona o acepta si su número es ("1234567890"). Así que básicamente eliminas el espacio y los caracteres no válidos haciendo una nueva variable para extraer solo los números. Luego llama a esos números con la aplicación UIApplication.

func callSellerPressed (sender: UIButton!){
        var newPhone = ""

        for (var i = 0; i < countElements(busPhone); i++){

            var current:Int = i
            switch (busPhone[i]){
                case "0","1","2","3","4","5","6","7","8","9" : newPhone = newPhone + String(busPhone[i])
                default : println("Removed invalid character.")
            }
        }

        if  (busPhone.utf16Count > 1){

        UIApplication.sharedApplication().openURL(NSURL(string: "tel://" + newPhone)!)
        }
        else{
            let alert = UIAlertView()
            alert.title = "Sorry!"
            alert.message = "Phone number is not available for this business"
            alert.addButtonWithTitle("Ok")
                alert.show()
        }
        }
 8
Author: Tom,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-17 21:03:58

Swift 3.0 y ios 10 o superior

func phone(phoneNum: String) {
    if let url = URL(string: "tel://\(phoneNum)") {
        if #available(iOS 10, *) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        } else {
            UIApplication.shared.openURL(url as URL)
        }
    }
}
 8
Author: Gandom,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-23 09:28:43

Las respuestas anteriores son parcialmente correctas, pero con "tel://" solo hay un problema. Una vez finalizada la llamada, volverá a la pantalla de inicio, no a nuestra aplicación. Así que mejor usar " telprompt://", volverá a la aplicación.

var url:NSURL = NSURL(string: "telprompt://1234567891")!
UIApplication.sharedApplication().openURL(url)
 7
Author: dipen baks,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-24 10:22:10

Estoy usando este método en mi aplicación y está funcionando bien. Espero que esto también te ayude.

func makeCall(phone: String) {
    let formatedNumber = phone.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet).joinWithSeparator("")
    let phoneUrl = "tel://\(formatedNumber)"
    let url:NSURL = NSURL(string: phoneUrl)!
    UIApplication.sharedApplication().openURL(url)
}
 6
Author: Ayath Khan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-27 05:07:19

Swift 3, iOS 10

func call(phoneNumber:String) {
        let cleanPhoneNumber = phoneNumber.components(separatedBy: CharacterSet.decimalDigits.inverted).joined(separator: "")
        let urlString:String = "tel://\(cleanPhoneNumber)"
        if let phoneCallURL = URL(string: urlString) {
            if (UIApplication.shared.canOpenURL(phoneCallURL)) {
                UIApplication.shared.open(phoneCallURL, options: [:], completionHandler: nil)
            }
        }
  }
 5
Author: LuAndre,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-08 23:23:17

En Swift 3,

if let url = URL(string:"tel://\(phoneNumber)"), UIApplication.shared.canOpenURL(url) {
     UIApplication.shared.openURL(url)
}
 4
Author: Venkadesh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-07 04:52:47

Esta es una actualización de la respuesta de @Tom usando Swift 2.0 Nota - Esta es toda la clase CallComposer que estoy usando.

class CallComposer: NSObject {

var editedPhoneNumber = ""

func call(phoneNumber: String) -> Bool {

    if phoneNumber != "" {

        for i in number.characters {

            switch (i){
                case "0","1","2","3","4","5","6","7","8","9" : editedPhoneNumber = editedPhoneNumber + String(i)
                default : print("Removed invalid character.")
            }
        }

    let phone = "tel://" + editedPhoneNumber
        let url = NSURL(string: phone)
        if let url = url {
            UIApplication.sharedApplication().openURL(url)
        } else {
            print("There was an error")
        }
    } else {
        return false
    }

    return true
 }
}
 3
Author: Michael McKenna,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-01 02:54:15

Estoy utilizando la solución swift 3 con validación de números

var validPhoneNumber = ""
    phoneNumber.characters.forEach {(character) in
        switch character {
        case "0"..."9":
            validPhoneNumber.characters.append(character)
        default:
            break
        }
    }

    if UIApplication.shared.canOpenURL(URL(string: "tel://\(validNumber)")!){
        UIApplication.shared.openURL(URL(string: "tel://\(validNumber)")!)
    }
 3
Author: Emmett,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-24 07:42:56

OpenURL() ha sido obsoleto en iOS 10. Aquí está la nueva sintaxis:

if let url = URL(string: "tel://\(busPhone)") {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
 2
Author: Torre Lasley,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-01 20:01:52

Para swift 3.0

if let url = URL(string: "tel://\(number)"), UIApplication.shared.canOpenURL(url) {
    if #available(iOS 10, *) {
        UIApplication.shared.open(url)
    } else {
        UIApplication.shared.openURL(url)
    }
}
else {
    print("Your device doesn't support this feature.")
}
 1
Author: Hardik Thakkar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-13 11:17:07

Solución Swift 3.0:

let formatedNumber = phone.components(separatedBy: NSCharacterSet.decimalDigits.inverted).joined(separator: "")
print("calling \(formatedNumber)")
let phoneUrl = "tel://\(formatedNumber)"
let url:URL = URL(string: phoneUrl)!
UIApplication.shared.openURL(url)
 0
Author: mazorati,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-04 10:09:47

Aquí hay una forma alternativa de reducir un número de teléfono a componentes válidos utilizando un Scanner {

let number = "+123 456-7890"

let scanner = Scanner(string: number)

let validCharacters = CharacterSet.decimalDigits
let startCharacters = validCharacters.union(CharacterSet(charactersIn: "+#"))

var digits: NSString?
var validNumber = ""
while !scanner.isAtEnd {
    if scanner.scanLocation == 0 {
        scanner.scanCharacters(from: startCharacters, into: &digits)
    } else {
        scanner.scanCharacters(from: validCharacters, into: &digits)
    }

    scanner.scanUpToCharacters(from: validCharacters, into: nil)
    if let digits = digits as? String {
        validNumber.append(digits)
    }
}

print(validNumber)

// +1234567890
 0
Author: Ashley Mills,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-24 15:54:12

Swift 3.0 y iOS 10+

UIApplication.shared.openURL(url) fue cambiado a UIApplication.shared.open(_ url: URL, options:[:], completionHandler completion: nil)

options and completion handler are optional, rendering:

UIApplication.shared.open(url)

Https://developer.apple.com/reference/uikit/uiapplication/1648685-open

 0
Author: RLoniello,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-28 21:40:11

Para un enfoque Swift 3.1 y compatible con versiones anteriores, haga lo siguiente:

@IBAction func phoneNumberButtonTouched(_ sender: Any) {
  if let number = place?.phoneNumber {
    makeCall(phoneNumber: number)
  }
}

func makeCall(phoneNumber: String) {
   let formattedNumber = phoneNumber.components(separatedBy: 
   NSCharacterSet.decimalDigits.inverted).joined(separator: "")

   let phoneUrl = "tel://\(formattedNumber)"
   let url:NSURL = NSURL(string: phoneUrl)!

   if #available(iOS 10, *) {
      UIApplication.shared.open(url as URL, options: [:], completionHandler: 
      nil)
   } else {
     UIApplication.shared.openURL(url as URL)
   }
}
 0
Author: Lauren Roth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-19 05:15:03

Si su número de teléfono contiene espacios, ¡elimínelos primero! Entonces puedes usar la solución de respuesta aceptada .

let numbersOnly = busPhone.replacingOccurrences(of: " ", with: "")

if let url = URL(string: "tel://\(numbersOnly)"), UIApplication.shared.canOpenURL(url) {
    if #available(iOS 10, *) {
        UIApplication.shared.open(url)
    } else {
        UIApplication.shared.openURL(url)
    }
}
 0
Author: iOSdev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-14 13:56:16