// 保存圖片到相簿(系統自動處理權限、重複檢測)
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
// 回調方法
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
if (error) {
NSLog(@"保存失敗: %@", error.localizedDescription);
} else {
NSLog(@"保存成功");
}
}
iOS 沒有直接「替換」API,標準流程:
PHAssetChangeRequest.deleteAssets,要求用戶授權「照片」完全訪問權限[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
// 1. 創建新資源
PHAssetCreationRequest *creation = [PHAssetCreationRequest creationRequestForAsset];
[creation addResourceWithType:PHAssetResourceTypePhoto data:imageData options:nil];
// 2. 刪除舊資源 (需 assetLocalIdentifier)
PHAsset *oldAsset = [PHAsset fetchAssetWithLocalIdentifiers:@[oldId] options:nil].firstObject;
[PHAssetChangeRequest deleteAssets:@[oldAsset]];
} completionHandler:^(BOOL success, NSError *error) {
if (success) NSLog(@"替換完成");
}];
NSPhotoLibraryAddUsageDescription 與 NSPhotoLibraryUsageDescriptionPHAssetChangeRequest.creationRequestForAssetFromImageAtFileURL 優化效能