Como fazer um telefonema no iOS 10 usando o Swift? [duplicado]
esta pergunta já tem uma resposta aqui:
- A ligar para um número de telefone no swift. 17 respostas
quero que a minha aplicação seja capaz de ligar para um determinado número quando um botão é clicado. Tentei pesquisá-lo no google, mas não parece ter um para o iOS 10 até agora (onde o openURL desapareceu). Alguém pode dar-me um exemplo de como o fazer? Para exemplo como:
@IBAction func callPoliceButton(_ sender: UIButton) {
// Call the local Police department
}
6 answers
if let url = URL(string: "tel://\(number)") {
UIApplication.shared.openURL(url)
}
For Swift 3+, you can use like
guard let number = URL(string: "tel://" + number) else { return }
UIApplication.shared.open(number)
OR
UIApplication.shared.open(number, options: [:], completionHandler: nil)
Certifica - te que limpaste o texto do teu número de telefone para remover todas as instâncias de (
, )
, -
, ou space
.
Tarefa
Faça uma chamada com o número de telefone validation
Detalhes
Xcode 9.2, Swift 4
Solução
extension String {
enum RegularExpressions: String {
case phone = "^\\s*(?:\\+?(\\d{1,3}))?([-. (]*(\\d{3})[-. )]*)?((\\d{3})[-. ]*(\\d{2,4})(?:[-.x ]*(\\d+))?)\\s*$"
}
func isValid(regex: RegularExpressions) -> Bool {
return isValid(regex: regex.rawValue)
}
func isValid(regex: String) -> Bool {
let matches = range(of: regex, options: .regularExpression)
return matches != nil
}
func onlyDigits() -> String {
let filtredUnicodeScalars = unicodeScalars.filter{CharacterSet.decimalDigits.contains($0)}
return String(String.UnicodeScalarView(filtredUnicodeScalars))
}
func makeAColl() {
if isValid(regex: .phone) {
if let url = URL(string: "tel://\(self.onlyDigits())"), UIApplication.shared.canOpenURL(url) {
if #available(iOS 10, *) {
UIApplication.shared.open(url)
} else {
UIApplication.shared.openURL(url)
}
}
}
}
}
Utilização
"+1-(800)-123-4567".makeAColl()
Amostra para ensaio
func test() {
isPhone("blabla")
isPhone("+1(222)333-44-55")
isPhone("+42 555.123.4567")
isPhone("+1-(800)-123-4567")
isPhone("+7 555 1234567")
isPhone("+7(926)1234567")
isPhone("(926) 1234567")
isPhone("+79261234567")
isPhone("926 1234567")
isPhone("9261234567")
isPhone("1234567")
isPhone("123-4567")
isPhone("123-89-01")
isPhone("495 1234567")
isPhone("469 123 45 67")
isPhone("8 (926) 1234567")
isPhone("89261234567")
isPhone("926.123.4567")
isPhone("415-555-1234")
isPhone("650-555-2345")
isPhone("(416)555-3456")
isPhone("202 555 4567")
isPhone("4035555678")
isPhone(" 1 416 555 9292")
}
private func isPhone(_ string: String) {
let result = string.isValid(regex: .phone)
print("\(result ? "" : "") \(string) | \(string.onlyDigits()) | \(result ? "[a phone number]" : "[not a phone number]")")
}
Resultado
Actualizado para Swift 3:
Usado abaixo de linhas simples de código, se quiser fazer uma chamada:
// função desfinização:
func makeAPhoneCall() {
let url: NSURL = URL(string: "TEL://1234567890")! as NSURL
UIApplication.shared.open(url as URL, options: [:], completionHandler: nil)
}
/ / function call: [usado em qualquer parte do seu código]
self.makeAPhoneCall()
Nota: Por favor, execute o aplicativo em um dispositivo real, porque ele não vai funcionar no simulador.
if let phoneCallURL:URL = URL(string: "tel:\(strPhoneNumber)") {
let application:UIApplication = UIApplication.shared
if (application.canOpenURL(phoneCallURL)) {
let alertController = UIAlertController(title: "MyApp", message: "Are you sure you want to call \n\(self.strPhoneNumber)?", preferredStyle: .alert)
let yesPressed = UIAlertAction(title: "Yes", style: .default, handler: { (action) in
application.openURL(phoneCallURL)
})
let noPressed = UIAlertAction(title: "No", style: .default, handler: { (action) in
})
alertController.addAction(yesPressed)
alertController.addAction(noPressed)
present(alertController, animated: true, completion: nil)
}
}
guard let url = URL(string: "tel://\(yourNumber)") else {
return //be safe
}
if #available(iOS 10.0, *) {
UIApplication.shared.open(url)
} else {
UIApplication.shared.openURL(url)
}
Temos de verificar se estamos a tomar o iOS 10 ou mais tarde, pois o'openURL' foi desactualizado nos iOS. 10.0
In Swift 4.2
func dialNumber(number : String) {
if let url = URL(string: "tel://\(number)"),
UIApplication.shared.canOpenURL(url) {
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:], completionHandler:nil)
} else {
UIApplication.shared.openURL(url)
}
} else {
// add error message here
}
}
Chama isto como abaixo
dialNumber(number: "+921111111222")
Espero que isto ajude.