How to share my current location to UIActivityViewController?

前端 未结 8 1402
别那么骄傲
别那么骄傲 2020-12-05 12:32

I know i can add things like text, URL, images to UIActivityViewController , but how to add my current location with a thumbnail of my location like in the tweet shown below

8条回答
  •  北荒
    北荒 (楼主)
    2020-12-05 12:55

    Solution using Swift 4.2 and CNContactVCardSerialization

     func vCardFilePath(from placemark: CLPlacemark) -> String? {
            let cnAddress = CNMutablePostalAddress()
            cnAddress.city = placemark.locality ?? ""
            cnAddress.country = placemark.country ?? ""
            cnAddress.postalCode = placemark.postalCode ?? ""
            cnAddress.isoCountryCode = placemark.isoCountryCode ?? ""
            cnAddress.state = placemark.administrativeArea ?? ""
            cnAddress.street = placemark.thoroughfare ?? ""
            let labelledAddress = CNLabeledValue(label: CNLabelOther, value: cnAddress)
    
            let abPerson = CNMutableContact()
            abPerson.givenName = locationName ?? ""
            abPerson.postalAddresses = [labelledAddress]
    
            if let coords = position?.coordinate,
                let loc = locationName?.addingPercentEncoding(withAllowedCharacters: .whitespacesAndNewlines) {
                let url = "https://maps.apple.com/?ll=\(coords.latitude),\(coords.longitude)&q=\(loc)" as NSString
                let urlAddress = CNLabeledValue(label: CNLabelHome, value: url)
                abPerson.urlAddresses = [urlAddress]
            }
    
            guard let vCards = try? CNContactVCardSerialization.data(with: [abPerson]) else {
                print("Couldn't extract vCards data")
                return nil
            }
            let vCardString = String(data: vCards, encoding: .utf8)
    
            //Store the vCard file
            let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
            let documentsDirectory = paths[0]
            let filePath = "\(documentsDirectory)/shareLocation.vcf"
    
            do {
                try vCardString?.write(toFile: filePath, atomically: false, encoding: .utf8)
            } catch _ {
                print("Couldn't write location .vcf file")
                return nil
            }
            return filePath
        }
    

提交回复
热议问题