iOS 8 比较麻烦,需要把数据写入临时文件,用临时文件的 URL 作为参数,调用 PHAssetChangeRequest 的类方法
复制代码
class func creationRequestForAssetFromImage(atFileURL fileURL: URL) -> Self?
以下是兼容 iOS 8 的写法
func saveImageData(_ data: Data) {
if #available(iOS 9.0, *) {
PHPhotoLibrary.shared().performChanges({
PHAssetCreationRequest.forAsset().addResource(with: .photo, data: data, options: nil)
}, completionHandler: { (success, error) in
// NOT on main thread
if success {
// Success
} else if let error = error {
// Handle error
}
})
} else {
// Write image data to temp file
let tempPath = NSTemporaryDirectory().appending("TempImageToSaveToPhoto.image")
let tempUrl = URL(fileURLWithPath: tempPath)
try? data.write(to: tempUrl)
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromImage(atFileURL: tempUrl)
}, completionHandler: { (success, error) in
// NOT on main thread
if success {
// Success
} else if let error = error {
// Handle error
}
// Remove temp file
try? FileManager.default.removeItem(at: tempUrl)
})
}
}
SDWebImage 缓存 UIImage、Data
SDWebImage (目前版本 4.0.0) 有两个方法可以使用。
SDWebImageManager 的方法
复制代码
- (void)saveImageToCache:(nullable UIImage *)image forURL:(nullable NSURL *)url;
SDImageCache 的方法
- (void)storeImage:(nullable UIImage *)image
imageData:(nullable NSData *)imageData
forKey:(nullable NSString *)key
toDisk:(BOOL)toDisk
completion:(nullable SDWebImageNoParamsBlock)completionBlock;

这个方法的 image、key 参数不能为空,否则直接执行 completionBlock 就返回。
从相册获取 UIImage、Data
UIImagePickerController 是常用的照片选取控制器。实现一个代理方法即可
复制代码
optional func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
通过 info 字典,可以获取 UIImage 等信息。这里用来查询 info 字典的 key 有
UIImagePickerControllerOriginalImage // 原始 UIImage
UIImagePickerControllerEditedImage // 编辑后的 UIImage
UIImagePickerControllerReferenceURL // ALAsset 的 URL
通过 ALAsset 的 URL 可获取 PHAsset。通过 PHImageManager 的方法可以获得相册图片的 Data










