[英]iOS UIImagePickerController how to save image right after taking image from camera
I am facing difficulties storing an image taken from the camera when using UIImagePickerController and getting its URL. 使用UIImagePickerController并获取其URL时,我在存储从相机拍摄的图像时遇到困难。
Checking the logs, I think it's because the taken image has no saved path on phone? 检查日志,我认为是因为所拍摄的图像在电话上没有保存的路径?
let imageUrl = info[UIImagePickerControllerImageURL] as? NSURL // logs show nil here
...
let localPath = photoURL.appendingPathComponent(imageName!) // crashes here due to forced unwrap of imageName (nil)
I wonder how I can fix this? 我不知道该如何解决? I have consulted other answers but none of them work (deprecated libraries or other issues).
我已经咨询了其他答案,但是它们都不起作用(不建议使用的库或其他问题)。
More complete code: 更完整的代码:
func openCamera() {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
imagePickerController.sourceType = .camera;
imagePickerController.allowsEditing = false
present(imagePickerController, animated: true, completion: nil)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
fatalError("error message")
}
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
let imageUrl = info[UIImagePickerControllerImageURL] as? NSURL // logs show nil here
let imageName = imageUrl?.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let photoURL = NSURL(fileURLWithPath: documentDirectory)
let localPath = photoURL.appendingPathComponent(imageName!) // crashes here due to forced unwrap of imageName (nil)
if !FileManager.default.fileExists(atPath: localPath!.path) {
do {
try UIImageJPEGRepresentation(image, 1.0)?.write(to: localPath!)
print("file saved")
}catch {
print("error saving file")
}
}
else {
print("file already exists")
}
...
dismiss(animated: true, completion: nil)
}
There is very easy function for this: 有一个非常简单的功能:
UIImageWriteToSavedPhotosAlbum(chosenImage, nil, nil, nil)
But I've also created helper class to deal with this. 但是我也创建了帮助程序类来解决这个问题。 Thanks to this helper you can save photo in specified album
多亏了这个助手,您可以将照片保存在指定的相册中
import Foundation
import Photos
final class PhotoAlbumHelper: NSObject {
static let albumName = "AppAlbum"
static let shared = PhotoAlbumHelper()
var assetCollection: PHAssetCollection?
var failedPhotos = [UIImage]()
func fetchAssetCollectionForAlbum() -> PHAssetCollection? {
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", PhotoAlbumHelper.albumName)
let collections = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
if let collection = collections.firstObject {
return collection
}
return nil
}
func createAlbum() {
PHPhotoLibrary.shared().performChanges({
PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: PhotoAlbumHelper.albumName) // create an asset collection with the album name
}) { [weak self] success, error in
if success {
guard let `self` = self else { return }
self.assetCollection = self.fetchAssetCollectionForAlbum()
while self.failedPhotos.count > 0 {
self.saveImage(self.failedPhotos.removeFirst())
}
} else {
print(error)
}
}
}
func saveImage(_ image: UIImage) {
assetCollection = fetchAssetCollectionForAlbum()
if assetCollection == nil {
failedPhotos.append(image)
createAlbum()
return
}
guard let album = assetCollection else { return }
PHPhotoLibrary.shared().performChanges({
let creationRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
guard let addAssetRequest = PHAssetCollectionChangeRequest(for: album) else { return }
let index = IndexSet(integer: 0)
addAssetRequest.insertAssets([creationRequest.placeholderForCreatedAsset!] as NSArray, at: index)
}, completionHandler: { success, error in
if !success {
print(error)
}
})
}
}
According to documentation : 根据文件:
A dictionary containing the original image and the edited image, if an image was picked;
包含原始图像和编辑图像(如果已选择图像)的词典; or a filesystem URL for the movie, if a movie was picked.
或电影的文件系统URL(如果已选择电影)。 The dictionary also contains any relevant editing information.
该词典还包含任何相关的编辑信息。 The keys for this dictionary are listed in Editing Information Keys.
该词典的键在“编辑信息键”中列出。
You cannot get the URL ( or you shouldn't ). 您无法获取URL(或不应获取)。 But you can have the image itself ( either in
UIImagePickerControllerEditedImage
or in UIImagePickerControllerOriginalImage
. 但是您可以拥有图像本身(在
UIImagePickerControllerEditedImage
或UIImagePickerControllerOriginalImage
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.