我有一些代码可以创建一个名为“content”的 NSSecureCoding 变量,我想将该变量转换为 NSData,然后可以将其制作成 UIImage 或发送到本地服务器。我该如何正确转换?我想要这个用于我在我的 iOS 应用程序中制作的共享扩展,因此当您在照片上按共享时,它会获取照片内容并将其转换为 NSData。这是我的代码:
inputItem = extensionContext!.inputItems.first as NSExtensionItem
attachment = inputItem.attachments![0] as NSItemProvider
if (attachment.hasItemConformingToTypeIdentifier(kUTTypeImage as String)){
attachment.loadItemForTypeIdentifier(kUTTypeImage as String,
options: nil,
completionHandler: {(content, error: NSError!) in
//insert code to convert "content"(NSSecureCoding) to NSData variable
})
}
最佳答案
DispatchQueue.global().async {
attachment.loadItem(forTypeIdentifier: kUTTypeImage as String, options: nil, completionHandler: { (item, error) in
if let error = error {
print(error.localizedDescription)
return
}
var image: UIImage?
if item is UIImage {
image = item as? UIImage
}
if item is URL {
let data = try? Data(contentsOf: item as! URL)
image = UIImage(data: data!)!
}
if item is Data {
image = UIImage(data: item as! Data)!
}
if let image = image {
DispatchQueue.main.async {
// image here
}
}
})
}
关于ios - 将 NSSecureCoding 转换为 NSData - Xcode - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29477544/