신속하게 전화 걸기
특정 번호를 사용하지 않고 변수로 전화를 거는 번호로 전화를 걸거나 적어도 전화에서 번호를 가져 오라고 말하려고합니다. 변수에서 호출되는이 숫자는 파서를 사용하거나 웹 사이트 SQL에서 가져 와서 검색 한 숫자입니다. 함수로 변수에 저장된 전화 번호를 호출하려고하는 버튼을 만들었지 만 아무 소용이 없었습니다. 감사합니다.
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)!)
}
단지 시도:
if let url = NSURL(string: "tel://\(busPhone)") where UIApplication.sharedApplication().canOpenURL(url) {
UIApplication.sharedApplication().openURL(url)
}
전화 번호가 busPhone
.
NSURL
의 init(string:)
너무 사용하여, 선택 사양 반환을 if let
우리가 확인 url
A는 NSURL
(이 아닌 NSURL?
의해 반환을 init
).
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)
}
}
다음과 같은 이유로 iOS 10 이상인지 확인해야합니다.
'openURL'은 iOS 10.0에서 더 이상 사용되지 않습니다.
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)
}
}
}
을 사용 callNumber("7178881234")
하여 전화를 걸 수 있어야합니다 .
스위프트 4,
private func callNumber(phoneNumber:String) {
if let phoneCallURL = URL(string: "telprompt://\(phoneNumber)") {
let application:UIApplication = UIApplication.shared
if (application.canOpenURL(phoneCallURL)) {
if #available(iOS 10.0, *) {
application.open(phoneCallURL, options: [:], completionHandler: nil)
} else {
// Fallback on earlier versions
application.openURL(phoneCallURL as URL)
}
}
}
}
Swift 3.0 및 iOS 10 이상
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)
}
}
}
위의 답변은 부분적으로 정확하지만 "tel : //"에는 한 가지 문제 만 있습니다. 통화가 끝나면 앱이 아닌 홈 화면으로 돌아갑니다. "telprompt : //"를 사용하는 것이 더 좋으므로 앱으로 돌아갑니다.
var url:NSURL = NSURL(string: "telprompt://1234567891")!
UIApplication.sharedApplication().openURL(url)
좋아, 도움을 받고 알아 냈어. 또한 전화 번호가 유효하지 않은 경우를 대비하여 멋진 경고 시스템을 설치했습니다. 내 문제는 내가 올바르게 부르고 있었지만 번호에 공백과 ( "123456-7890")과 같은 원하지 않는 문자가있었습니다. UIApplication은 귀하의 번호가 ( "1234567890") 인 경우에만 작동하거나 수락합니다. 따라서 기본적으로 숫자 만 가져 오는 새 변수를 만들어 공백과 잘못된 문자를 제거합니다. 그런 다음 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()
}
}
내 응용 프로그램 에서이 방법을 사용하고 있으며 잘 작동합니다. 이것이 당신에게도 도움이되기를 바랍니다.
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)
}
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)
}
}
}
스위프트 3에서는
if let url = URL(string:"tel://\(phoneNumber)"), UIApplication.shared.canOpenURL(url) {
UIApplication.shared.openURL(url)
}
번호 유효성 검사와 함께 신속한 3 솔루션을 사용하고 있습니다.
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)")!)
}
이것은 Swift 2.0을 사용 하는 @Tom 의 답변에 대한 업데이트입니다. 참고 -이것은 내가 사용하는 전체 CallComposer 클래스입니다.
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
}
}
openURL ()은 iOS 10에서 더 이상 사용되지 않습니다. 다음은 새로운 구문입니다.
if let url = URL(string: "tel://\(busPhone)") {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
Swift 3.0 solution:
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)
For 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.")
}
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)
Here's an alternative way to reduce a phone number to valid components using a 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
Swift 3.0 & iOS 10+
UIApplication.shared.openURL(url)
was changed to 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
For a Swift 3.1 & backwards compatible approach, do this:
@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)
}
}
If your phone number contains spaces, remove them first! Then you can use the accepted answer's solution.
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)
}
}
For Swift 4.2 and above
if let phoneCallURL = URL(string: "tel://\(01234567)"), UIApplication.shared.canOpenURL(phoneCallURL)
{
UIApplication.shared.open(phoneCallURL, options: [:], completionHandler: nil)
}
참고URL : https://stackoverflow.com/questions/27259824/calling-a-phone-number-in-swift
'IT TIP' 카테고리의 다른 글
프로그래머가 아닌 사람에게 프로그래밍이 "어떻게 생겼는지"설명 할 수있는 좋은 예는 무엇입니까? (0) | 2020.10.27 |
---|---|
선행 0으로 채우기 (0) | 2020.10.27 |
Objective C에서 3 자리 숫자에 쉼표를 추가하는 방법은 무엇입니까? (0) | 2020.10.27 |
Android 에뮬레이터가 보이지 않습니다. 어떻게 옮길 수 있습니까? (0) | 2020.10.27 |
Android Studio의 : app : compileDebugJavaWithJavac 작업에 대한 실행 실패 (0) | 2020.10.27 |