我有一些代码创建一个名为“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
})
}
答案 0 :(得分:2)
有点晚了,但今天发生在我身上,我这样解决了,
在completionHandler
:
if let data = content {
self.imageData = UIImage(data: NSData(contentsOfURL: data as! NSURL)!)
}
imageData是UIImage类型。
答案 1 :(得分:1)
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
}
}
})
}