使用UIImageWriteToSavedPhotosAlbum直接保存
//OC
- (void)saveButtonEventWithImage:(UIImage *)image
{
//保存完后调用的方法
SEL selector = @selector(onCompleteCapture:didFinishSavingWithError:contextInfo:);
//保存
UIImageWriteToSavedPhotosAlbum(image, self, selector, NULL);
}
//图片保存完后调用的方法
- (void)onCompleteCapture:(UIImage *)screenImage didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
if (error){
//保存失败
}else {
//保存成功
}
}
//swift
func saveButtonEventWithImage(image: UIImage) {
//保存完后调用的方法
let selector = #selector(ViewController.onCompleteCapture(image:error:contextInfo:))
//保存
UIImageWriteToSavedPhotosAlbum(image, self, selector, nil)
}
//图片保存完后调用的方法
func onCompleteCapture(image: UIImage, error: NSError?, contextInfo: UnsafeRawPointer) {
if error == nil {
//保存失败
}else {
//保存成功
}
}
优点:简单,方便
使用Photos框架提供的方法
//oc
- (void)getPhotoUrlSaveButtonEventWithImage:(UIImage *)image success: (void(^)(NSURL *photoUrl))completionHandler {
__weak typeof(self) weakSelf = self;
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAssetChangeRequest *result = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
PHObjectPlaceholder *assetPlaceholder = result.placeholderForCreatedAsset;
//imageLocalIdentifier用于零时存取相片的标识符,方便后边能够取出此相片
weakSelf.imageLocalIdentifier = assetPlaceholder.localIdentifier;
} completionHandler:^(BOOL success, NSError * _Nullable error) {
if (success) {
//保存成功后通过前边的identifier得到其路径
PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsWithLocalIdentifiers:@[weakSelf.imageLocalIdentifier] options:nil];
PHAsset *asset = assets[0];
[asset requestContentEditingInputWithOptions:nil completionHandler:^(PHContentEditingInput * _Nullable contentEditingInput, NSDictionary * _Nonnull info) {
completionHandler(contentEditingInput.fullSizeImageURL);
}];
}
}];
}
//swift
func getPhotoUrlSaveButtonEventWithImage(image: UIImage, completionHandler: @escaping ((URL) -> Void)) {
PHPhotoLibrary.shared().performChanges({ [weak self]() -> Void in
let result = PHAssetChangeRequest.creationRequestForAsset(from: image)
let assetPlaceholder = result.placeholderForCreatedAsset
if let identifier = assetPlaceholder?.localIdentifier {
//imageLocalIdentifier用于零时存取相片的标识符,方便后边能够取出此相片
self?.imageLocalIdentifier = identifier
}
}) { [weak self](success: Bool, error: Error?) in
if success {
//保存成功后通过前边的identifier得到其路径
let assets = PHAsset.fetchAssets(withLocalIdentifiers: [self!.imageLocalIdentifier], options: nil)
let asset = assets.firstObject
asset?.requestContentEditingInput(with: nil, completionHandler: { (contentEditingInput: PHContentEditingInput?, info: [AnyHashable : Any]) in
if let url = contentEditingInput?.fullSizeImageURL {
completionHandler(url)
}
})
}
}
}
注意:此方法需导入Photos库,并且#import <Photos/Photos.h>
优点:可以直接获取到保存后的路径,方便使用