1// Copyright 2015-present 650 Industries. All rights reserved.
2
3#import <EXMediaLibrary/EXSaveToLibraryDelegate.h>
4
5@interface EXSaveToLibraryDelegate ()
6
7@property (nonatomic, strong) EXSaveToLibraryCallback callback;
8
9@end
10
11@implementation EXSaveToLibraryDelegate : NSObject
12
13- (void)writeImage:(UIImage *)image withCallback:(EXSaveToLibraryCallback)callback
14{
15  _callback = callback;
16  UIImageWriteToSavedPhotosAlbum(image,
17                                 self,
18                                 @selector(image:didFinishSavingWithError:contextInfo:),
19                                 nil);
20}
21
22- (void)writeVideo:(NSString *)movieUrl withCallback:(EXSaveToLibraryCallback) callback
23{
24  _callback = callback;
25  UISaveVideoAtPathToSavedPhotosAlbum(movieUrl,
26                                      self,
27                                      @selector(video:didFinishSavingWithError:contextInfo:),
28                                      nil);
29}
30
31- (void)writeGIF:(NSURL *)gifUrl withCallback:(EXSaveToLibraryCallback) callback
32{
33  _callback = callback;
34  [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
35    NSData *data = [NSData dataWithContentsOfURL:gifUrl];
36    PHAssetCreationRequest *request = [PHAssetCreationRequest creationRequestForAsset];
37    [request addResourceWithType:PHAssetResourceTypePhoto data:data options:NULL];
38  } completionHandler:^(BOOL success, NSError *error) {
39    [self triggerCallback:nil withError:error];
40  }];
41}
42
43- (void)image:(UIImage*)image
44        didFinishSavingWithError:(NSError *)error
45        contextInfo:(void *)info
46{
47  [self triggerCallback:image withError:error];
48}
49
50- (void)video:(NSString *)videoPath
51        didFinishSavingWithError:(NSError *)error
52        contextInfo:(void *)contextInfo
53{
54  [self triggerCallback:videoPath withError:error];
55}
56
57- (void)triggerCallback:(id)asset
58              withError:(NSError *)error
59{
60  if (self.callback) {
61    self.callback(asset, error);
62  }
63}
64
65@end
66