如何将图像URL保存到照片库,然后使用保存的图像

Zhe*_*hen 4 url image objective-c uiimagepickercontroller ios

我正在为我的应用实施"在线图片搜索"功能.我需要的流程如下:

1)检索用户想要使用的图像URL

2)将图像(通过URL)保存到手机的相册中

3)通过图像选择器控制器检索保存的图像,并打开移动和缩放屏幕

4)使用从相册中检索的图像.

任何人都可以建议我在获取图像URL后如何执行上述步骤?

Ama*_*ulo 12

您可以使用此代码将图像保存在相册中

    UIImageWriteToSavedPhotosAlbum(yourImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);



- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error != NULL)
    {
        // handle error
    }
    else 
    {
        // handle ok status
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,为了在另一个线程中执行代码,我会编写这样的代码

// load data in new thread
[NSThread detachNewThreadSelector:@selector(downloadImage) toTarget:self withObject:nil];
Run Code Online (Sandbox Code Playgroud)

您可以在代码,按钮或任何其他UIKit控件中的任何位置使用此方法.那么你将需要做出艰苦工作的方法.

- (void)downloadImage
{

    // network animation on
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    // create autorelease pool
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 

   // save image from the web
    UIImageWriteToSavedPhotosAlbum([UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"your_image_address.com"]]], self, @selector(image:didFinishSavingWithError:contextInfo:), nil);

    [self performSelectorOnMainThread:@selector(imageDownloaded) withObject:nil waitUntilDone:NO ];  

    [pool drain];       

}

- (void)imageDownloaded
{

    // network animation off
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

    // do whatever you need to do after 
}
Run Code Online (Sandbox Code Playgroud)

  • 这太棒了.非常感谢您的时间和帮助.:) (2认同)