Search code examples
swiftcoordinatesshareuiactivityviewcontroller

Swift 5 - Sharing location using vCardURL


I am trying to share an address through UIActivityViewController.

This is how I get the URL:

func vCardURL(from coordinate: CLLocationCoordinate2D, with name: String?) -> URL {
    let vCardFileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("vCard.loc.vcf")
    let vCardString = [
        "BEGIN:VCARD",
        "VERSION:4.0",
        "FN:\(name ?? "Shared Location")",
        "item1.URL;type=pref:http://maps.apple.com/?ll=\(coordinate.latitude),\(coordinate.longitude)",
        "item1.X-ABLabel:map url",
        "END:VCARD"
        ].joined(separator: "\n")
    do {
        try vCardString.write(toFile: vCardFileURL.path, atomically: true, encoding: .utf8)
    } catch let error {
        print("Error, \(error.localizedDescription), saving vCard: \(vCardString) to file path: \(vCardFileURL.path).")
    }
        return vCardFileURL
}

func didTapShareButton() {        
    let coordinate = CLLocationCoordinate2D(latitude: 52.520007, longitude: 13.404954)
    let url = self.vCardURL(from: coordinate, with: "Berlin")
    let activityViewController = UIActivityViewController(activityItems: [url], applicationActivities: nil)

    //Here it opens the UIActivityViewController
    present(activityViewController, animated: true, completion: nil)
}

URL Output:

file:///Users/edoardodecal/Library/Developer/CoreSimulator/Devices/E1A8A47C-ABF7-4048-ACB1-0AC91E7E0B5B/data/Containers/Data/Application/F79E6A32-B2E7-4137-A75B-AFDE3294A1C2/tmp/vCard.loc.vcf

This is the result:

enter image description here

What I expect: enter image description here

Any hints? Thanks


Solution

  • Forget all this stuff. The only thing you need is to share the Apple Maps URL with the coordinates... That's it! Tested on iOS 14 with UIKit and SwiftUI.

    if let url = URL(string: "https://maps.apple.com?ll=\(latitude),\(longitude)") {
      let activity = UIActivityViewController(activityItems: [url], applicationActivities: nil)
    }
    

    And then show the View Controller...