gpt4 book ai didi

iOS UIImagePickerController 如何在从相机拍摄图像后立即保存图像

转载 作者:行者123 更新时间:2023-11-30 11:18:44 26 4
gpt4 key购买 nike

在使用 UIImagePickerController 并获取其 URL 时,我在存储从相机拍摄的图像时遇到了困难。

查看日志,我认为是因为拍摄的图像在手机上没有保存路径?

let imageUrl          = info[UIImagePickerControllerImageURL] as? NSURL // logs show nil here
...
let localPath = photoURL.appendingPathComponent(imageName!) // crashes here due to forced unwrap of imageName (nil)

我想知道如何解决这个问题?我咨询过其他答案,但没有一个有效(已弃用的库或其他问题)。

更完整的代码:

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)
}

最佳答案

有一个非常简单的功能:

UIImageWriteToSavedPhotosAlbum(chosenImage, nil, nil, nil)

但我还创建了辅助类来处理这个问题。感谢这个助手,您可以将照片保存在指定相册中

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)
}
})
}
}

关于iOS UIImagePickerController 如何在从相机拍摄图像后立即保存图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51518636/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com