Another option is to copy the file to the "documents" directory (which is writable). It uses a bit more code than the UIImageJPEGRepresentation
approach though so you may still prefer to use that technique instead. Perhaps use the "documents directory" approach if you really don't want to alter the original image (however, in theory, the difference between the original and one created using UIImageJPEGRepresentation
at 100% should be imperceptible).
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")
}
})
})
/var
directory isn't user writable on a physical device. See developer.apple.com/library/mac/documentation/FileManagement/… for full details (TL;DR: use/Documents
and/tmp
). – Mike McDonald