My objective is to convert an address into an Apple Maps link and share it with UIActivityViewController, and when it is clicked, it opens Apple Maps and displays an annotation with the address, along with the "directions" button at the bottom, etc. Pretty much make it seem link someone searched for that address. I am able to convert the address, and share the link. Additionally, when the link is clicked, Apple Maps opens, and is centred on my desired location. However, I am unable to create the annotation and include it in the link. I have attempted to make an annotation with the correct coordinates, but have no clue how to add it to the link. To make things less complicated, I removed the annotation code, but here is what I have so far.
func activityItems(latitude: Double, longitude: Double) -> [AnyObject]? {
//this function does most of the work, creating the link and returning it
var items = [AnyObject]()
let URLString = "https://maps.apple.com?ll=\(latitude),\(longitude)"
if let url = NSURL(string: URLString) {
items.append(url)
}
let locationVCardString = [
"BEGIN:VCARD",
"VERSION:3.0",
"PRODID:-//Joseph Duffy//Blog Post Example//EN",
"N:;Shared Location;;;",
"FN:Shared Location",
"item1.URL;type=pref:\(URLString)",
"item1.X-ABLabel:map url",
"END:VCARD"
].joined(separator: "\n")
guard let vCardData : NSSecureCoding = locationVCardString.data(using: .utf8) as NSSecureCoding? else {
return nil
}
let vCardActivity = NSItemProvider(item: vCardData, typeIdentifier: "kUTTypeVCard" as String)
let annotation = MKPointAnnotation()
annotation.coordinate.latitude = latitude
annotation.coordinate.longitude = longitude
items.append(vCardActivity)
items.append(annotation)
return items
}
@IBAction func sendAddress(_ sender: UIButton) {
//this is the IBAction func, from the button tap. it uses the other function to present the activityViewController.
let address = self.donation.object(forKey: "Address") as! String
let geoCoder = CLGeocoder()
geoCoder.geocodeAddressString(address) { placemarks, error in
if let error = error{
print(error.localizedDescription)
return
}
if let placemarks = placemarks{
if let location = placemarks[0].location{
let lat = location.coordinate.latitude
let long = location.coordinate.longitude
if let shareObject = self.activityItems(latitude: lat, longitude: long) {
// making activity view controller
let textToShare = [ shareObject.first, shareObject.last ]
let activityViewController = UIActivityViewController(activityItems: textToShare as [Any], applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash
// present
self.present(activityViewController, animated: true, completion: nil)
}
}
}
}
}