2014-01-29 218 views
3

我試圖將圖像從相機保存到照片庫,然後存儲保存的圖像的URL。我的代碼:將圖像保存到照片庫並獲取保存的圖像的URL

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { 

ALAssetsLibrary *library = [[ALAssetsLibrary alloc]init]; 
[library writeImageToSavedPhotosAlbum:(__bridge CGImageRef)([info objectForKey:UIImagePickerControllerOriginalImage]) 
          orientation:ALAssetOrientationUp completionBlock:^(NSURL *assetURL, NSError *error) { 
           if(error == nil) { 
            _myImageUrl = [NSString stringWithFormat:@"%@",assetURL]; 
            NSLog(@"%@",assetURL); 
           } else NSLog(@"%@",error); 
          }]; 

[picker dismissViewControllerAnimated:YES completion:nil];} 

我的問題是,assetUrl始終爲NULL。有任何想法嗎? 謝謝!

+0

可能與本文相關。可能是iOS7的錯誤。 [ALAssetsLibraryWriteVideoCompletionBlock返回未定義的值] [1] [1]:http://stackoverflow.com/questions/20813540/alassetslibrarywritevideocompletionblock-return-undefined-values – GregP

回答

0

最後,在閱讀更多內容後,我發現答案:函數的第一個參數是CGImageRef類型,而(__bridge CGImageRef)不符合我的預期;但如果我打電話UIImage對象的CGImage方法,它的工作原理。正確的方法是:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { 

    ALAssetsLibrary *library = [[ALAssetsLibrary alloc]init]; 
    CGImageRef image = [[info objectForKey:UIImagePickerControllerOriginalImage] CGImage]; 
    [library writeImageToSavedPhotosAlbum:image 
           orientation:ALAssetOrientationUp 
          completionBlock:^(NSURL *assetURL, NSError *error) { 
            if(error == nil) { 
             _myImageUrl = [NSString stringWithFormat:@"%@",assetURL]; 
             NSLog(@"%@",assetURL); 
            } else NSLog(@"%@",error); 
           }]; 

    self.toDoImage.image = [info objectForKey:UIImagePickerControllerOriginalImage]; 
    [picker dismissViewControllerAnimated:YES completion:nil]; 
}