swift - 如何获取用户库或相机中所选照片的​​ URL?

标签 swift

我有一个应用程序,用户可以在其中选择是要拍照还是从他们的库中选择一张照片。我拥有的代码获取了 Xcode 设备模拟器的图像 URL,但不适用于我的物理 iPhone。
当我使用个人设备选择图像时 我的结果会打印出来

Failed: There is a client side validation error for the field [local] with message: The file located at the `local` URL is missing. Make sure the file exists before uploading to storage.

但是当我使用设备模拟器运行时,它运行完美,图像存储在我的后端。我不确定为什么会发生这种情况。

我希望能够从我自己的设备获取 URL。

从 xcode 设备模拟器打印的 url
file:///Users/GBMR/Library/Developer/CoreSimulator/Devices/877A8184-D857-4211-94B1-00A6B724A956/data/Containers/Data/Application/094279FA-37B1-45E6-ABC4-ADAA08B5477B/PicturesB71286E4-1994-4D76-AC14-D40A062BC832.jpeg
Completed: ywassupo

从我的物理 iPhone 打印的 url
file:///var/mobile/Containers/Data/Application/C0415B3C-F50E-4D20-8D8A-941D29B9C4D1/Pictures9BA481F9-C52A-40FD-8A06-AAA2D6CDA6D7.jpeg
Failed: There is a client side validation error for the field [local] with message: The file located at the `local` URL is missing. Make sure the file exists before uploading to storage.

代码:
  func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

        if let selectedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
            imageView.image = selectedImage
            imageView.contentMode = .scaleAspectFit

            //            detect(image: ciimage)
            navigationItem.title = "Tap next to continue"
            nextButton.isEnabled = true

            if let imgUrl = info[UIImagePickerController.InfoKey.imageURL] as? URL{
                let imgName = imgUrl.lastPathComponent
                let documentDirectory = NSSearchPathForDirectoriesInDomains(.picturesDirectory, .allDomainsMask, true).first
                let localPath = documentDirectory?.appending(imgName)

                //let image = info[UIImagePickerController.InfoKey] as! UIImage
                let data = selectedImage.pngData()! as NSData
                data.write(toFile: localPath!, atomically: true)
                //let imageData = NSData(contentsOfFile: localPath!)!
                let photoURL = URL.init(fileURLWithPath: localPath!)
                let infoTVC = InfoTableViewController()
                infoTVC.imageChosenName = photoURL
                _ = Amplify.Storage.uploadFile(key: "ywassupo", local: photoURL ,resultListener: {(event) in
                    switch event{
                    case .success(let data):
                        print("Completed: \(data)")
                    case .failure(let storageError):
                        print("Failed: \(storageError.errorDescription). \(storageError.recoverySuggestion)")
                    }

                })
                //NSURL(fileURLWithPath: localPath!)
                print(photoURL)

                dismiss(animated:true, completion: nil)
            }
        }
    }

任何人都可以将我引导到正确的方向来解决这个问题吗?

最佳答案

UIImagePickerController不会为您提供所选图像的路径,您只需抓取图像 info[UIImagePickerControllerOriginalImage] as UIImage并通过提供目录路径保存到应用程序存储区域的本地。

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    guard let image = info[.editedImage] as? UIImage else { return }

    let imageName = UUID().uuidString
    let imagePath = getDocumentsDirectory().appendingPathComponent(imageName)

    if let jpegData = image.jpegData(compressionQuality: 0.8) {
        try? jpegData.write(to: imagePath)
    }

    dismiss(animated: true)
}

func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    return paths[0]
}

如果您只需要保存一张图像,它的效果很好。如果有多个图像,您需要编写一些逻辑来创建唯一的图像名称并将其保存到同一目录。

不要忘记在 info.plist 中添加以下键的权限

相机:
Key       :  Privacy - Camera Usage Description   
Value     :  <your project name> will use camera to capture photo.

照片:
Key       :  Privacy - Photo Library Usage Description    
Value     :  <your project name> will use photo library to select photo.

关于swift - 如何获取用户库或相机中所选照片的​​ URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62353389/

相关文章:

ios - 泛型参数受其他泛型参数约束

ios - Swift Avplayer - 当点击 'Play' 时,停止所有其他 tableviewcells 播放

ios - 如何通过应用程序打开 iCloud 设置

ios - 如何从另一个 ViewController 中的按钮更改单独 ViewController 中的 textView?

ios - 如何从场景停靠栏中删除点击手势识别器?

iOS自定义转场动画

ios - 核心数据好像没有保存

ios - 我想自己实现 promise ,但找不到解决方案

ios - 标注验证在给定的超时时间内未成功

ios - 导入自己的swift框架