UIImageJPEGRepresentation または UIImagePNGRepresentation を示唆する多くの回答があります。ただし、これらのソリューションは元のファイルを変換しますが、この質問は実際にはファイルをそのまま保存することに関するものです。
アセット ライブラリからファイルを直接アップロードすることはできないようです。ただし、実際の画像データを取得するために PHImageManager を使用してアクセスできます。方法は次のとおりです。
Swift 3 (Xcode 8、iOS 8.0 以降のみ)
1) 写真フレームワークをインポートする
import Photos
2) imagePickerController(_:didFinishPickingMediaWithInfo:) でアセット URL を取得します
3) fetchAssets(withALAssetURLs:options:) を使用してアセットをフェッチする
4) requestImageData(for:options:resultHandler:) で実際の画像データを取得します。このメソッドの結果ハンドラーには、データとファイルへの URL があります (URL はシミュレーターでアクセスできますが、残念ながらデバイスではアクセスできません - 私のテストでは startAccessingSecurityScopedResource() は常に false を返しました)。ただし、この URL はファイル名を見つけるのに役立ちます。
コード例:
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) }
}
}
})
}
}
これにより、正しい名前を含むそのままのファイルが提供され、アップロード用のマルチパート ボディを準備する際に、その UTI を取得して正しい MIME タイプを特定することもできます (ファイル拡張子を介して特定することもできます)。