如何通知控制器下载完成?

时间:2012-01-11 08:10:34

标签: iphone

我有一个使用NSURLConnection下载图像的课程。我是ios的新手,所以我想知道如何“通知”我的ViewController下载完成了吗?我应该使用什么“工具”?

澄清:

我已经实现了NsUrlConnection的所有回调,我的问题是如何通过我的connectionDidFinishLoading通知ViewController下载已完成?

4 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

我使用AFNetworking在其中使用块来处理连接响应成功或失败。它还有一个很好的包装器,用于检索图像并在UIImageView中加载。

答案 2 :(得分:0)

要使用NSURLConnection,您必须实现一个委托,该委托具有在连接发生有趣事件时将被调用的方法。这就是您如何获得有关建立连接,如何接收数据以及如何知道连接已完成的信息( connectionDidFinishLoading )的信息。 http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html#//apple_ref/doc/uid/20001836-BAJEAIEE

中的更多信息

因此,您在 connectionDidFinishLoading 中放置的代码基本上必须向视图控制器发送某种消息,以便更新视图。

答案 3 :(得分:0)

您应该在启动nsurl-connection的类中使用这些方法:

#pragma mark -
#pragma mark Download support (NSURLConnectionDelegate)

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.activeDownload appendData:data];
}


- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error // Never called (deprecated method not used with IOS version >> 4.3 ???)
{
    // Clear the activeDownload property to allow later attempts
    self.activeDownload = nil;

    // Release the connection now that it's finished
    self.imageConnection = nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    UIImage *image = [[UIImage alloc] initWithData:self.activeDownload];

    self.activeDownload = nil;
    // Release the connection now that it's finished
    self.imageConnection = nil;
}

其中imageConnection是NSURLConnection类型的属性:

NSURLConnection *imageConnection

和activeDownload是一个NSMutableData:

NSMutableData *activeDownload