UIActivityViewController 联系人共享? [英] UIActivityViewController contacts sharing?

查看:27
本文介绍了UIActivityViewController 联系人共享?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑一种使用 UIActivityViewController(或使用 SMS)从一个设备到另一个设备共享联系人的方法.

I'm trying to think about a way to share contact using UIActivityViewController (or using SMS) from one device to another.

到目前为止,我一直在寻找,但我不知道如何使用我的应用在设备之间共享联系人.

So far I've been looking and I've no idea how can I share contacts between devices using my app.

有什么想法吗?

推荐答案

找了几个月,我终于找到了实现这一目标的方法.

After searching for months, I have finally discovered the way to achieve this.

您可以使用此代码在 UIActivityViewController 中共享单个 CNContact:

You can use this code to share a single CNContact in a UIActivityViewController:

let contact: CNContact = /* your contact here */

let fileManager = NSFileManager.defaultManager()
let cacheDirectory = try! fileManager.URLForDirectory(NSSearchPathDirectory.CachesDirectory, inDomain: NSSearchPathDomainMask.UserDomainMask, appropriateForURL: nil, create: true)

let fileLocation = cacheDirectory.URLByAppendingPathComponent("\(CNContactFormatter().stringFromContact(contact)!).vcf")

let contactData = try! CNContactVCardSerialization.dataWithContacts([contact])
contactData.writeToFile(fileLocation.path!, atomically: true)

let activityVC = UIActivityViewController(activityItems: [fileLocation], applicationActivities: nil)
presentViewController(activityVC, animated: true, completion: nil)

此代码将联系人转换为其 NSData 表示形式,将其保存到应用的缓存文件夹中,并将文件作为活动项共享.

This code converts the contact into its NSData representation, saves it to the app's cache folder, and shares the file as an activity item.

如果要共享多个联系人,可以通过这种方式传递多个文件.

If you want to share multiple contacts, you can pass multiple files in this way.

let contact: CNContact = /* your contact here */

let fileManager = FileManager.default
let cacheDirectory = try! fileManager.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true)

let fileLocation = cacheDirectory.appendingPathComponent("\(CNContactFormatter().string(from: contact)!).vcf")

let contactData = try! CNContactVCardSerialization.data(with: [contact])
do {
    try contactData.write(to: fileLocation.asURL(), options: .atomicWrite)
} catch {
    ...
}

let activityVC = UIActivityViewController(activityItems: [fileLocation], applicationActivities: nil)
present(activityVC, animated: true, completion: nil)

这篇关于UIActivityViewController 联系人共享?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆