2015-10-13 86 views
0

我正在構建一個帶屏幕截圖按鈕的應用程序。現在我想要將此應用中製作的所有屏幕截圖保存在同一個自定義名稱應用專輯中。我已經知道如何在應用程序第一次打開代碼時創建相冊。總是將截圖保存在「照片」中相同的自定義名稱應用程序相冊中

-(void)createAppAlbum 
{ 

[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ 
    PHAssetCollectionChangeRequest *changeRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:@"App Album Name"]; 
    albumPlaceholder = changeRequest.placeholderForCreatedAssetCollection; 

} 

completionHandler:^(BOOL success, NSError *error) { 
         if (success) { 
         fetchResult = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[albumPlaceholder.localIdentifier] options:nil]; 
              assetCollection = fetchResult.firstObject; 

} 
         else { 
           NSLog(@"Error creating album: %@", error);} 
            }]; 

} 

所以我的應用程序創建一個名爲「應用程序專輯名稱」專輯: 我與像照片框架創建我的專輯。 我能夠把我的截圖保存在我的新專輯按鈕,如:

-(IBAction)screenshot:(id)sender 
{ 

if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) 
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, [UIScreen mainScreen].scale); 
else 
    UIGraphicsBeginImageContext(self.view.bounds.size); 

[self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; 
UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 


[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ 
    PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image]; 

    PHAssetCollectionChangeRequest *assetCollectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection]; 
    [assetCollectionChangeRequest addAssets:@[[assetChangeRequest placeholderForCreatedAsset]]]; 
} completionHandler:^(BOOL success, NSError *error) { 
    if (!success) { 
     NSLog(@"Error creating asset: %@", error); 
    } 
}]; 

}

如果我離開這個的viewController,並取回後,我想找到的專輯,我已經創建,並保存在同一張專輯中的另一個屏幕截圖,因爲我不想每次進入此視圖控制器時都創建一個。

所以我的問題是,我將如何得到這張專輯我的名字創建了第一次,然後在保存新的屏幕截圖

+0

的[iOS版保存在一個應用程序特定相冊照片](可能的複製http://stackoverflow.com/questions/11972185/ios-save-photo-in-an-app-specific-album) – Fennelouski

+0

@Fennelouski - iOS 5,也沒有使用Photo框架。 – MOzeb

+0

你能解釋一下難題嗎?當你創建相冊時,你會得到它的標識符。從此,通過其標識符訪問相冊。你有什麼困難? – matt

回答

0

因爲這個問題是專門針對,針對iOS 8,該代碼會工作得很好。

- (void)saveImage:(UIImage *)image { 
    if (!self.library) { 
     self.library = [[ALAssetsLibrary alloc] init]; 
    } 

    __weak ALAssetsLibrary *lib = self.library; 

    [self.library addAssetsGroupAlbumWithName:@"My Photo Album" resultBlock:^(ALAssetsGroup *group) { 

     ///checks if group previously created 
     if(group == nil){ 

      //enumerate albums 
      [lib enumerateGroupsWithTypes:ALAssetsGroupAlbum 
           usingBlock:^(ALAssetsGroup *g, BOOL *stop) 
      { 
       //if the album is equal to our album 
       if ([[g valueForProperty:ALAssetsGroupPropertyName] isEqualToString:@"My Photo Album"]) { 

        //save image 
        [lib writeImageDataToSavedPhotosAlbum:UIImagePNGRepresentation(image) metadata:nil 
              completionBlock:^(NSURL *assetURL, NSError *error) { 

               //then get the image asseturl 
               [lib assetForURL:assetURL 
                resultBlock:^(ALAsset *asset) { 
                 //put it into our album 
                 [g addAsset:asset]; 
                } failureBlock:^(NSError *error) { 

                }]; 
              }]; 

       } 
      }failureBlock:^(NSError *error){ 

      }]; 

     }else{ 
      // save image directly to library 
      [lib writeImageDataToSavedPhotosAlbum:UIImagePNGRepresentation(image) metadata:nil 
            completionBlock:^(NSURL *assetURL, NSError *error) { 

             [lib assetForURL:assetURL 
              resultBlock:^(ALAsset *asset) { 

               [group addAsset:asset]; 

              } failureBlock:^(NSError *error) { 

              }]; 
            }]; 
     } 

    } failureBlock:^(NSError *error) { 

    }]; 
} 

要測試工作的,我創建了一個單一屏幕應用,增加了一個按鈕的視圖,並補充,需要一個屏幕截圖,隨後將圖像提供給saveImage:功能的方法。下面是我添加到它使代碼它的工作:

#import <AssetsLibrary/AssetsLibrary.h> 

@interface ViewController() 
@property (nonatomic, strong) UIButton *screenshotButton; 
@property (nonatomic, strong) ALAssetsLibrary *library; 
@end 

@implementation ViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 

    [self.view addSubview:self.screenshotButton]; 
} 

- (UIButton *)screenshotButton { 
    if (!_screenshotButton) { 
     _screenshotButton = [[UIButton alloc] initWithFrame:CGRectInset(self.view.bounds, 100.0f, 120.0f)]; 
     _screenshotButton.layer.borderColor = [UIColor blueColor].CGColor; 
     _screenshotButton.layer.borderWidth = 2.0f; 
     _screenshotButton.layer.cornerRadius = 5.0f; 
     [_screenshotButton setTitle:@"Take Screenshot" forState:UIControlStateNormal]; 
     [_screenshotButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; 
     [_screenshotButton addTarget:self action:@selector(takeScreenshot) forControlEvents:UIControlEventTouchUpInside]; 
    } 

    return _screenshotButton; 
} 

- (void)takeScreenshot { 
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) 
     UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, [UIScreen mainScreen].scale); 
    else 
     UIGraphicsBeginImageContext(self.view.bounds.size); 

    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; 
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    NSData * imgData = UIImagePNGRepresentation(image); 
    if(imgData) 
     [imgData writeToFile:@"screenshot.png" atomically:YES]; 
    else 
     NSLog(@"error while taking screenshot"); 


    UIColor *randomColor = [UIColor colorWithHue:((CGFloat)(arc4random()%255)/255.0f) 
             saturation:((CGFloat)(arc4random()%255)/200.0f) 
             brightness:((CGFloat)(arc4random()%100)/255.0f) + 0.5f 
              alpha:1.0f]; 
    self.screenshotButton.layer.borderColor = randomColor.CGColor; 
    [self.screenshotButton setTitleColor:randomColor forState:UIControlStateNormal]; 

    [self saveImage:image]; 
} 

有幾件事情需要注意:

  • AssetsLibrary在iOS版9已經過時,所以不建議 的iOS後使用8,但仍然有效。
  • 這可以實現和 使用任何UIImage傳遞到saveImage:,所以它可以工作,即使 如果您使用其他庫。
  • 確保包含#import <AssetsLibrary/AssetsLibrary.h>
  • 更改「我的相冊」,以正確的專輯名稱,並可能設置靜態
+0

使用Photo Kit可以輕鬆解決問題;使用資產庫只是一個柺杖。 – matt

+0

太棒了!我只是添加了If語句,創建文件夾,如果用戶刪除它。謝謝! – MOzeb

+0

我並不反對它不理想,並且可能有更好的選擇,更適合iOS 9,但這確實有效並符合iOS 8的要求。 – Fennelouski

相關問題