Reputation: 344
To export image to phone gallery I tried use ALAssetsLibrary but Xcode 8.0 inform me that method is deprecated and I should use PHPhotoLibrary. When I use ALAssetsLibrary then method looks like that:
#import <AssetsLibrary/AssetsLibrary.h>
-(void)exportToGallery{
ALAssetsLibrary *assetsLib = [ALAssetsLibrary new];
[assetsLib writeImageToSavedPhotosAlbum:image
metadata:[image properties];
completionBlock:nil;
}
How can I use PHPhotoLibrary to have the same effect?
Upvotes: 1
Views: 1763
Reputation: 14571
There is a way to do that.
Objective C
Import the Photos Framework
#import <Photos/Photos.h>
Then make your image
UIImage * image = [UIImage imageNamed:@"DP.jpg"];
Then save the image. The image will be saved to Camera Roll.
This will work same as writeImageToSavedPhotosAlbum
of ALAssetsLibrary
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
[PHAssetChangeRequest creationRequestForAssetFromImage:image];
} completionHandler:^(BOOL success, NSError *error) {
if (success) {
NSLog(@"Image Saved");
}
else {
NSLog(@"error in saving image : %@",error);
}
}];
Make sure the permission for photos is ON.
Also if you have created the project of Xcode 8, then you need to add a key in Info.plist
<key>NSPhotoLibraryUsageDescription</key>
<string>Use Photos</string>
You can also use the creationRequestForAssetFromImage
method not only with UIImage making but also with an image URL too.
These are the methods you can use from Photos Framework.
+ (instancetype)creationRequestForAssetFromImage:(UIImage *)image;
+ (nullable instancetype)creationRequestForAssetFromImageAtFileURL:(NSURL *)fileURL;
+ (nullable instancetype)creationRequestForAssetFromVideoAtFileURL:(NSURL *)fileURL;
Swift 3.0
let image = UIImage(named: "DP.jpg")
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAsset(from: image!)
}) { (success:Bool, error:Error?) in
if success {
print("Image Saved Successfully")
} else {
print("Error in saving:"+error.debugDescription)
}
}
The other methods for Photos Framework for Swift are:
open class func creationRequestForAsset(from image: UIImage) -> Self
open class func creationRequestForAssetFromImage(atFileURL fileURL: URL) -> Self?
open class func creationRequestForAssetFromVideo(atFileURL fileURL: URL) -> Self?
Upvotes: 4