swift中添加图片到相册中
实例代码
1.拿到照片后,写入系统的相册.
UIImageWriteToSavedPhotosAlbum(image!,self,#selector(image(image:didFinishSavingWithError:contextInfo:)), nil)
2.需要实现系统的didFinishSavingWithError方法
func image(image:UIImage, didFinishSavingWithError error : NSError?, contextInfo : AnyObject) {
if (error != nil) { print(error!) }
}
注意点:以下是进入文档内容,只提供了OC的方法,没有提供swift中的方法.所以要自己把OC的转成swift的方法...
// Adds a photo to the saved photos album. The optional completionSelector should have the form:
// - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
iOS10之后 记得在info-plist里边配置Privacy - Photo Library Usage Description
swift中从相册里边获取照片
1.创建UIImagePickerController对象,设置数据源和代理,跳转到图片选择控制器
func imageFormPhotosAlbum(){
let picker = UIImagePickerController()
//设置代理
picker.delegate = self
//设置数据源(从相册或者相机)
picker.sourceType = .photoLibrary
self.present(picker, animated: true, completion: nil)
}
2.监听选择完照片后返回照片
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
根据UIImagePickerControllerOriginalImage从info里边取值
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
picker .dismiss(animated: true, completion: nil)
}
3.监听取消选择后的按钮
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
print("取消了")
picker.dismiss(animated: true, completion: nil)
}