使用此代码,我从共享扩展中提取图像并将其写入我在应用程序组中创建的目录。
let content = self.extensionContext!.inputItems[0] as! NSExtensionItem
let contentType = kUTTypeImage as String
for attachment in content.attachments as! [NSItemProvider] {
if attachment.hasItemConformingToTypeIdentifier(contentType) {
attachment.loadItem(forTypeIdentifier: contentType, options: nil) { data, error in
// from here
if error == nil {
let url = data as! NSURL
let originalFileName = url.lastPathComponent
if let imageData = NSData(contentsOf: url as URL) {
let img = UIImage(data:imageData as Data)
if let data = UIImagePNGRepresentation(img!) {
// write, etc.
}
}
}
}
一切正常。
我想知道的是是否可以减少一些代码:特别是,之后if error == nil
,我:
- 将数据转换为
NSURL
; - 用于
NSURL
得到一个NSData
; - 用于
NSData
得到一个UIImage
; - 用于
UIImage
得到一个UIImagePNGRepresentation
;
除了避免创建 imageData 变量之外,没有办法(安全地)以更少的步骤实现相同的目标吗?