iOS保存图片至沙盒目录

这个没有什么任何难点,就是有时会因为一个方法或参数写错会导致保存失败,从而影响开发效率,浪费时间。所以记录一下正确代码
1. 获取图片

@IBAction func takePhoto(_ sender: Any) {
        let vc = UIImagePickerController()
        vc.sourceType = .camera
        vc.showsCameraControls = true
        vc.delegate = self
        self.present(vc, animated: true, completion: nil)
    }

showsCameraControls属性可以不设置,默认值true。如果要设置的话一定要放在sourceType属性后面。否则会报错。

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Source type must be UIImagePickerControllerSourceTypeCamera'
libc++abi.dylib: terminating with uncaught exception of type NSException

看这个错误信息还以为枚举值设置的有问题

2. 保存图片

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        guard let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else { return }
        guard let imageData = image.pngData() as NSData? else { return }
        let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first ?? ""
        let pictureName = "picture.png"
        let path = documentPath+"/"+pictureName
        //1.String
        if imageData.write(toFile: path, atomically: true) {
            print("保存成功")
        } else {
            print("保存失败")
        }
        //2.URL
        let url = URL(fileURLWithPath: path)
        if imageData.write(to: url, atomically: true) {
            print("保存成功")
        } else {
            print("保存失败")
        }
        
        print(FileManager.default.subpaths(atPath: documentPath))
        
        picker.dismiss(animated: true, completion: nil)
    }

最后保存图片可以用String类型路径,也可以用URL。使用URL必须使用URL(fileURLWithPath: path)生成fileURL

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。