iOS 相册和网络图片的存取
保存 UIImage 到相册
UIKit
UIKit 中一个古老的方法,Objective-C 的形式
void UIImageWriteToSavedPhotosAlbum(UIImage *image, id completionTarget, SEL completionSelector, void *contextInfo);
保存完成后,会调用 completionTarget 的 completionSelector。如果 completionTarget 不为空,completionTarget 必须实现以下方法
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
Objective-C 的写法
- (void)saveImage:(UIImage *)image {
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
if (error) {
// Fail
} else {
// Success
}
}
Swift 的写法
func saveImage(_ image: UIImage) {
UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) {
if error == nil {
// Success
} else {
// Fail
}
}
Photos framework
iOS 8 开始,可以用 Photos framework。PHAssetChangeRequest 的类方法可以保存 UIImage
class func creationRequestForAsset(from image: UIImage) -> Self
编辑相册需要在 PHPhotoLibrary 的闭包中进行,有两种方法
func performChanges(_ changeBlock: @escaping () -> Void, completionHandler: ((Bool, Error?) -> Void)? = nil)
func performChangesAndWait(_ changeBlock: @escaping () -> Void) throws
以上两种方法,分别是异步和同步执行。一般用第一种异步执行的方法,不会阻塞主线程。
func saveImage(_ image: UIImage) {
PHPhotoLibrary.shared().performChanges({