ios - 使用相机模式拍摄图像时出错

标签 ios iphone swift

我正在使用相机图库开发图像选择器,并使用以下代码获取从相机捕获的图像,但imageurl和图像名称为零。我正在使用操作系统版本 11.2.2 的移动设备上进行测试。

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    let image = info[UIImagePickerControllerOriginalImage] as! UIImage
    let imageUrl          = info[UIImagePickerControllerReferenceURL] as? NSURL
    let imageName         = imageUrl?.lastPathComponent
    let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
    let photoURL          = NSURL(fileURLWithPath: documentDirectory)
    let localPath         = photoURL.appendingPathComponent(imageName!)

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

最佳答案

使用UIImagePickerControllerImageURL而不是UIImagePickerControllerReferenceURL,如下所示:

let imageUrl = info[UIImagePickerControllerImageURL] as? NSURL

关于ios - 使用相机模式拍摄图像时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49146822/

相关文章:

swift - 即使在 Xcode 10.1 中自定义后, TableView 仍然显示基本

ios - 长按时单元格 ImageView 更改

iphone - 诊断崩溃日志(针对一系列与 UIKit 相关的崩溃)?

ios - 如何在 Swift 3 中为来自 web 服务的 Json 响应创建模型类

ios - 在 ios 7 中以编程方式切换飞行模式

ios - 使用私有(private)框架以编程方式发送 iMessage

ios - 翠鸟: 'setBackgroundImage(with:for:placeholder:options:progressBlock:completionHandler:)' 的使用不明确

ios - Swift贝塞尔曲线填充渐变填充

ios - UIBarButtonItem(自定义 View :) -- not tappable

ios - 如何在 Interface Builder 中为 3.5” 和 4” Retina 定位 View ?