coctile
coctile

Reputation: 83

How can I share location from my app to WhatsApp in Swift 3

I'm trying to share a location from my iOS app to WhatsApp and I want it to look like this:

enter image description here

What I'm doing is sending vCard with this code :

 func vCardURL(from coordinate: CLLocationCoordinate2D, with name: String?) -> URL {
    let vCardFileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("Shared Location.loc.vcf")

    let vCardString = [
        "BEGIN:VCARD",
        "VERSION:3.0",
        //"PRODID:-//Apple Inc.//iPhone OS 10.3.2//EN",
        "N:;My Location;;;",
        "FN:My Location",
        "item1.URL;type=pref:https://maps.apple.com/?ll=50.359890\\,12.934560&q=My%20Location&t=m",
        "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).")
    }

    print(vCardString)

    return vCardFileURL
} // end of function

// calling the methood above

let vURL = LocationVCard.vCardURL(from: self.newLocation.coordinate, with: "Berlin")

                let activityViewController = UIActivityViewController(activityItems: [vURL], applicationActivities: nil)
                self.present(activityViewController, animated: true, completion: nil)

But I always end up with this style instead of what I want: enter image description here

Upvotes: 6

Views: 1245

Answers (1)

Hejazi
Hejazi

Reputation: 17015

No need to save the vCard string to a file, just convert it to Data and wrap it with NSItemProvider with the correct type identifier public.vcard, and it'll work just fine:

let data = vCardString.data(using: .utf8)! as NSData
let item = NSItemProvider(item: data, typeIdentifier: "public.vcard")
let activityViewController = UIActivityViewController(activityItems: [item], applicationActivities: nil)

Upvotes: 3

Related Questions