【问题标题】:Making a phone call with swift not working with certain numbers使用 swift 拨打电话无法使用某些号码
【发布时间】:2019-05-27 08:13:23
【问题描述】:

在过去的几个小时里,我一直在拼命尝试在调用此函数时使用 swift 拨打电话。

    func callPhone(phoneNumber: String){
        guard let url = URL(string:"telprompt:\(phoneNumber)") else {
             print("failed to load url, phone number: \(phoneNumber)")

             return
        }
        UIApplication.shared.open(url)
    }

由于某种原因它不起作用,我在网上到处搜索,仍然找不到为什么它不起作用的问题。有些数字偶尔会起作用,比如如果我尝试“123456789”它会起作用。但如果我尝试不同的号码,它就行不通了;守卫 let 语句不起作用,并且 url 将为空。 请帮我。非常感谢任何反馈。

编辑:所以我发现它什么时候不起作用,但我不知道如何解决它。当我从苹果地图获取电话号码时它不起作用,但是当我硬编码电话号码时它起作用。 这是我的完整代码:

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

@IBOutlet weak var map: MKMapView!
let locationManager = CLLocationManager()
let regionMeters : Double = 10000

override func viewDidLoad() {
    super.viewDidLoad()

    map.delegate = self
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()
    map.showsUserLocation = true
    if let location = locationManager.location?.coordinate {
        let region = MKCoordinateRegion.init(center: location, latitudinalMeters: regionMeters, longitudinalMeters: regionMeters)

        map.setRegion(region, animated: true)
    }
    searchLocations(search: "Restaurant")

}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    let identifier = "Place"
        var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)

        if annotationView == nil {

            annotationView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: identifier)
            annotationView!.canShowCallout = true

            let btn = UIButton(type: .contactAdd)

            annotationView!.rightCalloutAccessoryView = btn
        } else {
            annotationView!.annotation = annotation
        }

        return annotationView
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {

    let subtitle = view.annotation?.subtitle as! String
    let splitted = subtitle.components(separatedBy: "+")
    let number = splitted.last as! String
    let trimmedNumber : String = number.components(separatedBy: [" ", "-", "(", ")"]).joined()
    CallOnPhone(phoneNumber: trimmedNumber)

}
func searchLocations(search : String){
    let searchRequest = MKLocalSearch.Request()
    searchRequest.naturalLanguageQuery = search
    searchRequest.region = map.region

    let activeSearch = MKLocalSearch(request: searchRequest)
    activeSearch.start { (response, err) in
        if response == nil {
            print("no request")
        } else {
            for item in (response?.mapItems)!{
                let annotation = MKPointAnnotation()
                annotation.title = item.name

                if let phone = item.phoneNumber {
                    annotation.subtitle = "Phone Number: \(phone as String)"
                }

                annotation.coordinate = item.placemark.coordinate
                self.map.addAnnotation(annotation)
            }



        }
    }
}

@objc func CallOnPhone(phoneNumber: String){
    let newStringPhone = phoneNumber.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
    print(newStringPhone)
    if newStringPhone != ""{
        if let url = URL(string: "tel://\(newStringPhone)"), UIApplication.shared.canOpenURL(url) {
            if #available(iOS 10, *) {
                UIApplication.shared.open(url)
            } else {
                UIApplication.shared.openURL(url)
            }
        }
    }

}

}

谢谢,

【问题讨论】:

  • 你能举一个无效数字的例子吗?
  • 你好,还是不行
  • 在我的 iPhone 上工作。你遇到了什么错误?
  • 我没有收到任何错误,只是没有加载 url

标签: ios iphone swift apple-maps


【解决方案1】:

下面的代码显示了点击按钮时调用一个数字。如果 phonenum 有空格,也会删除空格。

var phoneNumber = "Phone Number: 1234567"
var finalNumber = ""

let number = phoneNumber.split(separator: ":")
let tempNum = "\(number.last ?? "")"
print(tempNum)
let trimmedNumber : String = tempNum.components(separatedBy: [" ", "-", "(", ")"]).joined()
print(trimmedNumber)
finalNumber = trimmedNumber
print(finalNumber)

btn_Call.addTarget(self, action: #selector(CallOnPhone), for: .touchUpInside)

@objc func CallOnPhone(sender:UIButton){
    let newStringPhone = finalNumber.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
    print(newStringPhone)
    if newStringPhone != ""{
        if let url = URL(string: "tel://\(newStringPhone)"), UIApplication.shared.canOpenURL(url) {
            if #available(iOS 10, *) {
                UIApplication.shared.open(url)
            } else {
                UIApplication.shared.openURL(url)
            }
        }
    }

}

【讨论】:

  • 你用的是什么版本的swift
  • 我使用的是 swift 4.2
  • 嗨,你能把你的代码发给我看看吗?它必须像在我的 iPhone 上一样工作。还分享您的电话号码字符串
  • 你确定,我怎么把它发给你?
  • 你在做什么 - 让 number = splitted.last as!细绳。你能把那个贴出来吗
【解决方案2】:

尝试修剪电话号码。

let myphone:String = phoneNumber.trimmingCharacters(in:.whitespacesAndNewlines)

完整代码:

if let url = URL(string: "tel://\(myphone)"),UIApplication.shared.canOpenURL(url) {
        if #available(iOS 10, *) {
            UIApplication.shared.open(url, options: [:], completionHandler:nil)
        } else {
            UIApplication.shared.openURL(url)
        }
    } else {
        Util.shared.showToast(message: "Can't make call from this device", view: self.view)
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多