0

我有一个 UIImageView,它使用 URL 显示图像,我有一个下载按钮,它会打开一个 UIActionSheet,然后使用 URL 下载文件我想知道如何使用 NSURLConnection 对其下载部分进行编码。

- (IBAction)DownloadClick:(id)sender {

    UIActionSheet *Action = [[UIActionSheet alloc]
                         initWithTitle:@"Options" 
                         delegate:self 
                         cancelButtonTitle:@"Cancel" 
                         destructiveButtonTitle:nil
                         otherButtonTitles:@"Download", nil];

    [Action showInView:self.view];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {

    if (buttonIndex == 0) {  //The Download code will go here This is where i need ur help


          }

Url 保存在名为“Url”的字符串中。

4

3 回答 3

1

利用异步请求进行图像下载。它还可以帮助您识别图像下载过程中的错误(如果有)。

 NSURL* url = [NSURL URLWithString:@"http://imageAddress.com"];
 NSURLRequest* request = [NSURLRequest requestWithURL:url];


[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response,
    NSData * data,
    NSError * error) {
if (!error){
            UIImage* image = [[UIImage alloc] initWithData:data];
           // do whatever you want with image
           }

}];
于 2013-04-24T08:18:09.013 回答
1

我认为您没有为此尝试过 Google。无论如何,这是您的代码,不要忘记添加NSURLConnectionDataDelegate

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0) {  //The Download code will go here This is where i need ur help

    //-------------------------------------------------------
    NSURL *url = [NSURL URLWithString:@"your_data_url"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy
                                         timeoutInterval:60.0];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    if (connection) {
        NSLog(@"succeed...");
    } else {
        NSLog(@"Failed...");
    }
    //-------------------------------------------------------------------
  }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

}
于 2013-04-24T08:21:32.717 回答
0

如果您需要同步下载,您可以尝试以下代码:

NSURL *imageUrl = [NSURL URLWithString:@"http://site.com/imageName.ext"];
NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
UIImage *image = [[UIImage alloc] initWithData:imageData];

现在您有了可以使用的图像。

如果您需要异步请求,我建议您阅读NSURLConnectionDataDelegate,它可以帮助您处理文件的下载。

于 2013-04-24T08:10:12.890 回答