您的位置:首页 > 移动开发 > IOS开发

iOS9图片保存到相册

2015-10-07 10:52 363 查看
[PHPhotoLibrary
requestAuthorization:^(
PHAuthorizationStatus status ) {

// To preserve the metadata, we create an asset from the JPEG NSData representation.

// Note that creating an asset from a UIImage discards the metadata.

// In iOS 9, we can use -[PHAssetCreationRequest addResourceWithType:data:options].

// In iOS 8, we save the image to a temporary file and use +[PHAssetChangeRequest creationRequestForAssetFromImageAtFileURL:].

if ( [PHAssetCreationRequest
class] ) {

[[PHPhotoLibrary
sharedPhotoLibrary]
performChanges:^{

[[PHAssetCreationRequest
creationRequestForAsset]
addResourceWithType:PHAssetResourceTypePhoto
data:imageData
options:nil];

} completionHandler:^(
BOOL success,
NSError *error ) {

if ( ! success ) {

NSLog(
@"Error occurred while saving image to photo library: %@", error );

}

}];

}

else {
// iOS8

NSString *temporaryFileName = [NSProcessInfo
processInfo].globallyUniqueString;

NSString *temporaryFilePath = [NSTemporaryDirectory()
stringByAppendingPathComponent:[temporaryFileName
stringByAppendingPathExtension:@"jpg"]];

NSURL *temporaryFileURL = [NSURL
fileURLWithPath:temporaryFilePath];

[[PHPhotoLibrary
sharedPhotoLibrary]
performChanges:^{

NSError *error =
nil;

[imageData writeToURL:temporaryFileURL
options:NSDataWritingAtomic
error:&error];

if ( error ) {

NSLog(
@"Error occured while writing image data to a temporary file: %@", error );

}

else {

[PHAssetChangeRequest
creationRequestForAssetFromImageAtFileURL:temporaryFileURL];

}

} completionHandler:^(
BOOL success,
NSError *error ) {

if ( ! success ) {

NSLog(
@"Error occurred while saving image to photo library: %@", error );

}

// Delete the temporary file.

[[NSFileManager
defaultManager]
removeItemAtURL:temporaryFileURL
error:nil];

}];
}

}];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: