There are lots of answers that suggest UIImageJPEGRepresentation or UIImagePNGRepresentation. But these solutions will convert the original file while this question is actually about saving the file AS IS.
It looks like uploading the file directly from assets library is impossible. But it can be accessed using PHImageManager to get the actual image data. Here's how:
Swift 3 (Xcode 8, only for iOS 8.0 and higher)
1) Import the Photos framework
import Photos
2) In the imagePickerController(_:didFinishPickingMediaWithInfo:) get the asset URL
3) Fetch assets using fetchAssets(withALAssetURLs:options:)
4) Get the actual image data with requestImageData(for:options:resultHandler:). In the result handler of this method you will have the data as well as URL to the file (the URL can be accessed on Simulator, but unfortunately is not accessible on the device - in my tests startAccessingSecurityScopedResource() always returned false). However this URL is still useful to find out the file name.
Example code:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
dismiss(animated: true, completion: nil)
if let assetURL = info[UIImagePickerControllerReferenceURL] as? URL,
let asset = PHAsset.fetchAssets(withALAssetURLs: [assetURL], options: nil).firstObject,
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first,
let targetURL = Foundation.URL(string: "file://(documentsPath)") {
PHImageManager.default().requestImageData(for: asset, options: nil, resultHandler: { (data, UTI, _, info) in
if let imageURL = info?["PHImageFileURLKey"] as? URL,
imageData = data {
do {
try data.write(to: targetURL.appendingPathComponent(imageURL.lastPathComponent), options: .atomic)
self.proceedWithUploadFromPath(targetPath: targetURL.appendingPathComponent(imageURL.lastPathComponent))
} catch { print(error) }
}
}
})
}
}
This will give you the file AS IS including its correct name and you can even get its UTI to determine correct mimetype (in addition to determining it via file extension) while preparing multipart body for upload.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…