1

使用此代码,我从共享扩展中提取图像并将其写入我在应用程序组中创建的目录。

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 变量之外,没有办法(安全地)以更少的步骤实现相同的目标吗?

4

1 回答 1

1

首先,您需要使用 nativeDataURL不是NSData&NSURL如果您想写入文件,DocumentDirectory那么您可以直接使用该 imageData 而无需从中创建UIImage对象,然后使用UIImagePNGRepresentation.

if let url = data as? URL, error == nil {

    let originalFileName = url.lastPathComponent
    if let imageData = try? Data(contentsOf: data) {
        // write, etc.
        var destinationURL  = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        destinationURL.appendPathComponent("fileName.png")
        try? imageData.write(to: destinationURL)
    }
}
于 2016-11-28T09:22:12.360 回答