另一种选择是将文件复制到“文档”目录(可写)。它使用的代码比该UIImageJPEGRepresentation
方法多一点,因此您可能仍然更喜欢使用该技术。如果您真的不想更改原始图像,也许可以使用“文档目录”方法(但是,理论上,原始图像与使用UIImageJPEGRepresentation
100% 创建的图像之间的差异应该是难以察觉的)。
asset.requestContentEditingInput(with: options, completionHandler: {(contentEditingInput: PHContentEditingInput?, info: [AnyHashable : Any]) -> Void in
let originalFileUrl = contentEditingInput!.fullSizeImageURL!
/* Copy file from photos app to documents directory */
let fileManager = FileManager.default
let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
let destinationPath = documentsDirectory.appendingPathComponent(originalFileUrl.lastPathComponent)
let destinationUrl = URL(fileURLWithPath: destinationPath)
do {
try fileManager.copyItem(at: originalFileUrl, to: destinationUrl)
}
catch {
print("Unable to copy file from photos to documents directory (run out of space on device?)")
return
}
/* Create metadata etc. for Firebase... */
/* Upload file to Firebase */
fileRef.putFile(from: destinationUrl, metadata: metadata, completion: { (metadata, error) in
// Remove the file from the documents directory
do {
try fileManager.removeItem(at: destinationUrl)
}
catch {
print("Unable to remove file from documents directory")
}
})
})