首页 > 解决方案 > 如何在动作扩展中将 NSSecureCoding 转换为 MKMapItem

问题描述

我正在尝试为我的应用程序制作一个操作扩展,用户可以在其中添加他当前的位置以及其他一些数据。在与 Apple Maps App 共享位置后,我调试了扩展程序,发现 Maps 发送了四个具有以下内容的提供商:

以上所有内容均为NSSecureCoding. 强制转换为 vCard 的数据Data并使用该数据进行初始化,纯文本和 url 从 NSSecureCoding 成功,但我还没有找到从收到的数据创建对象的方法。StringStringMKMapItem

这是我尝试过的:

provider.loadItem(forTypeIdentifier: "com.apple.mapkit.map-item", options: nil) { (content, _) in
    let item = content as! MKMapItem

}

但它失败了。我可能必须Data先将它转换为,但我找不到任何初始化MKMapItemData

标签: iosswiftnssecurecoding

解决方案


使用 NSKeyedUnarchiver

itemProvider.loadItem(forTypeIdentifier: "com.apple.mapkit.map-item", options: nil) { (item, error) in

    guard let data = item as? Data else { return }

    do {
         guard let mapItem = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? MKMapItem else { return }
         print(mapItem)
    } catch {
         print("Error unarchiving mapItems, \(error)")
    }

推荐阅读