我试图将UIImage保存到相机胶卷。
Apple不推荐使用UIImageWriteToSavedPhotosAlbum
,因此我避免使用{ALAssets
),强制使用PhotoLibrary
。
这是我使用的代码:
定义:
var rollCollection : PHAssetCollection!;
初始化:
let result = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .SmartAlbumUserLibrary, options: nil);
rollCollection = result.firstObject as? PHAssetCollection;
保存图片的代码:
if (rollCollection != nil){
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
let assetRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(
self.originalImg!);
let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: self.rollCollection!);
let assetPlaceHolder = assetRequest.placeholderForCreatedAsset;
albumChangeRequest!.addAssets([assetPlaceHolder!])
}, completionHandler: { success, error in
dispatch_async(dispatch_get_main_queue(), {
print ("\(error!)");
if (!success){
self.presentViewController(self.alertCantSave!, animated: false, completion: nil);
}
else {
self.presentViewController(self.alertSaved!, animated: false, completion: nil);
}
});
})
}
else {
dispatch_async(dispatch_get_main_queue(), {
self.presentViewController(self.alertCantSave!, animated: false, completion: nil);
});
}
每次我尝试保存图片时都会出现以下错误:
Error Domain=NSCocoaErrorDomain Code=-1 "(null)"
有什么想法吗? 我无法找到任何解释,在我找到的任何地方,我都找到了类似于我的代码片段(包括Apple的文档:https://developer.apple.com/library/ios/documentation/Photos/Reference/PHPhotoLibrary_Class/)
感谢。
答案 0 :(得分:3)
我在几个小时内寻找完全相同的东西后才发现这个问题。
玩了一下我能够得到一个对我有用的答案,所以我在这里分享它,以防万一其他人在将来寻找类似的东西。
// Make sure the image is not nil
guard let image = image else {
// No image here...
return
}
// Perform changes to the library
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
// You only need to create the request, there is no need to define the placeholder
// nor to add the asset because swift does not like it when you try to modify the camera roll.
PHAssetChangeRequest.creationRequestForAssetFromImage(image)
}, completionHandler: { success, error in
// Same as what you have...
})
如果您想要一个如何将图像保存到自定义相册并从自定义相册查询图像的示例,请查看此答案。 Save images with PHImageManager