0

i have some following json data :

This will all show in map view. So when user press any pins in map. The address, name call button will display.

I have one action method for that call button..So if any user press any pin in my map. it will show the Address, name, one call button... So if user press that call button , it show show the respective or correct phone number of my name and address and it should show in normal phone dial pad.

I did some what in objective - c. But i am not good in swift 2.0.

Can any one help me out how to do that.

Full code:

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)
    }

In that i tried :

@IBAction func CallButtontap(sender: AnyObject) {

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

}

It din't work

Final updated:

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)
}

}

user5513630
  • 1,709
  • 8
  • 24
  • 48

2 Answers2

2

Here is the swift version of your code:

@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")
    }
}

Also mark this useful website: https://objectivec2swift.com/#/converter/code

Kenan Karakecili
  • 731
  • 6
  • 23
  • Please note that, "telpromt is just an code i have get in my previous code. Please tell me with my json data. Then how to call that number with respective name and correct address – user5513630 Mar 22 '16 at 08:47
  • Actually i get that pieace of code form So. But i dont know why they have added `telprompt`.I dont have any label to display the number. When i press call button , that number should be redirect to dial pad .. And that number should be correct number of my `name and address` of my map pin...( please see my post explaniation ) – user5513630 Mar 22 '16 at 09:00
  • please help me out – user5513630 Mar 22 '16 at 09:46
0

Try following swift code :

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

The code will hep you to call directly as well get back in your app after call.

Thank you.

Losiowaty
  • 7,911
  • 2
  • 32
  • 47
vivek agravat
  • 251
  • 2
  • 10
  • Please note that, "telpromt is just an code i have get in my previous code. Please tell me with my json data. Then how to call that number with respective name and correct address – user5513630 Mar 22 '16 at 08:47
  • Actually i get that pieace of code form So. But i dont know why they have added `telprompt`.I dont have any label to display the number. When i press call button , that number should be redirect to dial pad .. And that number should be correct number of my `name and address` of my map pin...( please see my post explaniation ) – user5513630 Mar 22 '16 at 09:00
  • in my consloe : here is no registered handler for URL scheme telprompt – user5513630 Mar 22 '16 at 09:31