Open maps with lat,long and link based iOS swift

 Problem:

I want a common function that i can handle one location object with lat,long and address.That address can have a link that copied from other apps like google maps,Apple maps and whatsapp.

Also want save option that will save the location into my app local database.

How to achieve all the above us.

Solution:

func openMaps(lat: Double,long: Double,address:String = "",isSave:Bool = true) {

    let addressURL = URL(string: address.trimStr ?? "")

    if let topview = UIApplication.topViewController() {

        if (lat != 0 && long != 0) {

            let actionSheet = UIAlertController(title: "", message: "", preferredStyle: .actionSheet)


            if let add = addressURL,UIApplication.shared.canOpenURL(add) {

                actionSheet.addAction(UIAlertAction(title: "Open", style: .default, handler: { _ in

                    UIApplication.shared.open(add)

                }))

            } else {

                actionSheet.addAction(UIAlertAction(title: "Google Maps", style: .default, handler: { _ in

                    if let url = URL(string: "https://maps.google.com/?q=@\(lat),\(long)") {

                        UIApplication.shared.open(url, options: [:], completionHandler: nil)

                    }

                }))

                actionSheet.addAction(UIAlertAction(title: "Apple Maps", style: .default, handler: { _ in

                    let coordinate = CLLocationCoordinate2DMake(lat,long)

                    let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: coordinate, addressDictionary: nil))

                    mapItem.name = address != "" ? address : "Destination"

                    mapItem.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving])

                }))

            }

            if isSave {

                actionSheet.addAction(UIAlertAction(title: "Save", style: .default, handler: { _ in

                    saveLocation(lat: lat, long: long, address: address)

                }))

            }

            actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

            if actionSheet.actions.count == 2 {

                if let add = addressURL,UIApplication.shared.canOpenURL(add) {

                    UIApplication.shared.open(add)

                }

            } else {

                topview.present(actionSheet, animated: true, completion: nil)

            }

        }

       else {

            if let topController = UIApplication.topViewController() {

                topController.view.makeToast("error location")

            }


        }

    }

}

Comments

Popular posts from this blog

Invalid bundle error while upload the app to the app Store

Convert NsNumber, NSDate to String in iOS Swift

Global LocationManager Singleton class iOS Swift