【问题标题】:How to get the phone number and show that number in phone dial pad when user press contact number inside my app当用户在我的应用程序中按下联系号码时,如何获取电话号码并在电话拨号盘中显示该号码
【发布时间】:2016-07-08 23:40:58
【问题描述】:

我有一些以下 json 数据:

这将全部显示在地图视图中。因此,当用户按下地图中的任何引脚时。将显示地址、姓名呼叫按钮。

我有一个action method 用于那个call button..所以如果任何用户按下我地图中的任何图钉。它将显示Address, name, one call button...因此,如果用户按下该呼叫按钮,它将显示我的name and address 的相应或正确电​​话号码,并且它应该显示在普通电话拨号盘中。

我在客观上做了一些事情 - c。但我在 swift 2.0 中表现不佳。

谁能帮我看看怎么做。

完整代码:

import UIKit
import MapKit
import CoreLocation

class mapVC: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

    @IBOutlet weak var mapView: MKMapView!

    @IBOutlet weak var AddressTitleLabel: UILabel!

    @IBOutlet weak var AddressSubtitleLabel: UILabel!

    @IBOutlet weak var LocationView: UIView!

    @IBOutlet weak var ResultCounts: UILabel!

    @IBOutlet weak var AddressImg: UIImageView!

    let locationManager = CLLocationManager()


    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()

        mapSearch()

        LocationView.hidden = true
        locationManager.delegate = self

        locationManager.desiredAccuracy = kCLLocationAccuracyBest


        mapView.delegate = self


    }

    func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {

        print("Inside selecting annotation")

       LocationView.hidden = false

        if let newTitle = view.annotation?.title, let newAddress = view.annotation?.subtitle, let AddressNewImage = view.detailCalloutAccessoryView {

            AddressTitleLabel.text = newTitle

            AddressSubtitleLabel.text = newAddress

            //setting callout accessory as image to UIImage
            UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0);

            AddressNewImage.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)

            let NAimage:UIImage = UIGraphicsGetImageFromCurrentImageContext();

            AddressImg.image = NAimage

        }

    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location : CLLocationCoordinate2D = manager.location!.coordinate;
        let long = location.longitude;
        let lat = location.latitude;
        CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in
            if (error != nil) {
                print("Reverse geocoder failed with error" + error!.localizedDescription)
                return
            }
        })

        let loadlocation = CLLocationCoordinate2D(
            latitude: lat, longitude: long

        )

        mapView.centerCoordinate = loadlocation;

        let span = MKCoordinateSpanMake(0.2, 0.2)
        let region = MKCoordinateRegion(center: loadlocation, span: span)


        mapView.setRegion(region, animated: true)

        let annotation = MKPointAnnotation()
        annotation.coordinate = loadlocation
        annotation.title = "Current Location"
        annotation.subtitle = "You are Here."

        mapView.addAnnotation(annotation)

        locationManager.stopUpdatingLocation();
    }

    func mapSearch(){

        //Map search for Level Income in the selected region area
        let url:NSURL = NSURL(string: "url")!
        let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data:NSData?, response: NSURLResponse?, error:NSError?) -> Void in

            do {
                let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray



                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    self.ResultCounts.text = "\(json.count) Results"

                    // Loop through all items and display them on the map

                    var lon:Double!

                    var lat:Double!

                    var annotationView:MKPinAnnotationView!

                    var pointAnnoation:LocationClass!

                    //2
                    for item in json{

                        let obj = item as! Dictionary<String,AnyObject>

                        lon = obj["longitude"]!.doubleValue

                        lat = obj["latitude"]!.doubleValue

                        pointAnnoation = LocationClass()

                        pointAnnoation.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lon)

                        pointAnnoation.title = obj["name"] as? String

                        pointAnnoation.subtitle = obj["address"] as? String

                        pointAnnoation.pinCustomImageName = "other_location.png"

                        let ImageName = obj["image"] as? String

                        let imgURL: NSURL = NSURL(string: ImageName!)!

                        let request: NSURLRequest = NSURLRequest(URL: imgURL)

                        let session = NSURLSession.sharedSession()

                        let Imgtask = session.dataTaskWithRequest(request){
                                (data, response, error) -> Void in

                                if (error == nil && data != nil)
                                {
                                    func display_image()
                                    {
                                        pointAnnoation.DisplayImage = UIImage(data: data!)
                                    }

                                    dispatch_async(dispatch_get_main_queue(), display_image)
                                }

                            }

                            Imgtask.resume()

                        annotationView = MKPinAnnotationView(annotation: pointAnnoation, reuseIdentifier: "pin")

                        self.mapView.addAnnotation(annotationView.annotation!)

                    }

                })

            }catch{
                print("Some error occured")
            }



        }

        // Call the resume() method to start the NSURLSession task
        task.resume()
    }

    func mapView(mapView: MKMapView,
        viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView?{

            let reuseIdentifier = "pin"

            var v = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseIdentifier)
            if v == nil {
                v = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseIdentifier)
                v!.canShowCallout = false
            }
            else {
                v!.annotation = annotation
            }

            let customPointAnnotation = annotation as! LocationClass

            v!.image = UIImage(named:customPointAnnotation.pinCustomImageName)

            v!.detailCalloutAccessoryView = UIImageView(image: customPointAnnotation.DisplayImage)

            return v
    }



    @IBAction func CallButtontap(sender: AnyObject) {

        let phoneUrl: NSURL = NSURL(string: "telprompt:\(item[index]["phone"])")!
        if UIApplication.sharedApplication().canOpenURL(phoneUrl) {
            UIApplication.sharedApplication().openURL(phoneUrl)
        }
    }


    func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
        print("Error while updating location " + error.localizedDescription)
    }

我试过了:

@IBAction func CallButtontap(sender: AnyObject) {

let phoneUrl: NSURL = NSURL(string: "telprompt:\(item[index]["phone"])")!
if UIApplication.sharedApplication().canOpenURL(phoneUrl) {
    UIApplication.sharedApplication().openURL(phoneUrl)
}

}

没用

最终更新:

func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {

        print("Inside selecting annotation")

       LocationView.hidden = false

        if let newTitle = view.annotation?.title, let newAddress = view.annotation?.subtitle, let AddressNewImage = view.detailCalloutAccessoryView {

            AddressTitleLabel.text = newTitle

            AddressSubtitleLabel.text = newAddress

            //setting callout accessory as image to UIImage
            UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0);

            AddressNewImage.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)

            let NAimage:UIImage = UIGraphicsGetImageFromCurrentImageContext();

            AddressImg.image = NAimage
            if (view.annotation is Annotation.self) {
                var annot: Annotation = view.annotation
                var index: Int = self.arrayOfAnnotations.indexOfObject(annot)
                CallButtontap(index)
            }

        }


    }

@IBAction func CallButtontap(sender: AnyObject) {

let phoneUrl: NSURL = NSURL(string: "telprompt:\(item[sender]["phone"])")!
if UIApplication.sharedApplication().canOpenURL(phoneUrl) {
    UIApplication.sharedApplication().openURL(phoneUrl)
}

}

【问题讨论】:

    标签: ios objective-c swift swift2


    【解决方案1】:

    这是您的代码的 swift 版本:

    @IBAction func didTapPhoneButton(sender: UIButton) {
        // This function  will make phone call 
        let phoneUrl: NSURL = NSURL(string: "telprompt:\(myJson[index]["phone"])")!
        if UIApplication.sharedApplication().canOpenURL(phoneUrl) {
            UIApplication.sharedApplication().openURL(phoneUrl)
        } else {
            PCUtilities.showAlertWithTitle("Alert", message: "Call facility is not available!!!", cancelButtonTitle: "OK")
        }
    }
    

    也标记这个有用的网站:https://objectivec2swift.com/#/converter/code

    【讨论】:

    • 请注意,“telpromt 只是我在以前的代码中得到的一个代码。请用我的 json 数据告诉我。然后如何用相应的名称和正确的地址拨打该号码
    • 实际上我得到了那段代码形式所以。但我不知道他们为什么添加telprompt。我没有任何标签来显示数字。当我按下呼叫按钮时,该号码应重定向到拨号盘..并且该号码应该是我的地图针的name and address 的正确号码...(请参阅我的帖子说明)
    • 请帮帮我
    【解决方案2】:

    尝试以下 swift 代码:

    @IBAction func btn_callTapped(sender: AnyObject) {
            let number = "1234567890" //set user number here.
            let phoneNumber: String = "telprompt://" + number
            UIApplication.sharedApplication().openURL(NSURL(string: phoneNumber)!)
    }
    

    代码将帮助您直接调用以及在调用后返回您的应用程序。

    谢谢。

    【讨论】:

    • 请注意,“telpromt 只是我在以前的代码中得到的一个代码。请用我的 json 数据告诉我。然后如何用相应的名称和正确的地址拨打该号码
    • 实际上我得到了那段代码形式所以。但我不知道他们为什么添加telprompt。我没有任何标签来显示数字。当我按下呼叫按钮时,该号码应重定向到拨号盘..并且该号码应该是我的地图针的name and address 的正确号码...(请参阅我的帖子说明)
    • 在我的控制台中:这里没有 URL 方案 telprompt 的注册处理程序
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多