尝试使用以下代码将图像保存在iphone画廊中,但在模拟器中工作正常,而不在iphone中。

-(void)saveTkt
{
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
CGRect rect = [keyWindow bounds];
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[keyWindow.layer renderInContext:context];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData * data = UIImagePNGRepresentation(img);
[data writeToFile:@"f.png" atomically:YES];

UIImageWriteToSavedPhotosAlbum(img, self, @selector(thisImage:hasBeenSavedInPhotoAlbumWithError:usingContextInfo:), nil);
}


编辑代码

-(void)saveTkt
{
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
CGRect rect = [keyWindow bounds];
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[keyWindow.layer renderInContext:context];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData * data = UIImagePNGRepresentation(img);
[data writeToFile:@"f.png" atomically:YES];

ALAuthorizationStatus status = [ALAssetsLibrary authorizationStatus];
if (status != ALAuthorizationStatusAuthorized) {
    //show alert for asking the user to give permission

}

//UIImageWriteToSavedPhotosAlbum(img, self, @selector(thisImage:hasBeenSavedInPhotoAlbumWithError:usingContextInfo:), nil);

ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

[library writeImageToSavedPhotosAlbum:[img CGImage] orientation:(ALAssetOrientation)[img imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
    if (error) {
        // TODO: error handling
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"error" message:[error localizedDescription] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    } else {
        // TODO: success handling
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"alert" message:@"Saved suceesfully in photos album." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }
}];

ALAssetsLibraryGroupsEnumerationResultsBlock assetGroupEnumerator =
^(ALAssetsGroup *assetGroup, BOOL *stop) {
    if (assetGroup != nil) {
        // do somthing
    }
};

ALAssetsLibraryAccessFailureBlock assetFailureBlock = ^(NSError *error) {
    NSLog(@"Error enumerating photos: %@",[error description]);

};

NSUInteger groupTypes = ALAssetsGroupAll;

[library enumerateGroupsWithTypes:groupTypes usingBlock:assetGroupEnumerator failureBlock:assetFailureBlock];

}

最佳答案

添加框架资产库

 ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

[library writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation)[image imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
if (error) {
// TODO: error handling
} else {
// TODO: success handling
}
}];
[library release];

10-07 17:22