Iphone 如何通知控制器下载已完成?
我有一个类可以下载带有NSURLConnection的图像。我是ios新手,所以我想知道如何“通知”我的ViewController下载已完成?我应该使用什么“工具” 澄清:Iphone 如何通知控制器下载已完成?,iphone,Iphone,我有一个类可以下载带有NSURLConnection的图像。我是ios新手,所以我想知道如何“通知”我的ViewController下载已完成?我应该使用什么“工具” 澄清: 我已经实现了NsUrlConnection的所有回调,我的问题是如何从我的ConnectionIDFinishLoading通知ViewController下载已完成?我使用块来处理成功或失败的连接响应。它还有一个很好的包装器,用于检索图像并加载到UIImageView中。要使用NSURLConnection,您必须实现一
我已经实现了NsUrlConnection的所有回调,我的问题是如何从我的ConnectionIDFinishLoading通知ViewController下载已完成?我使用块来处理成功或失败的连接响应。它还有一个很好的包装器,用于检索图像并加载到UIImageView中。要使用NSURLConnection,您必须实现一个委托,该委托具有在连接发生有趣的事情时调用的方法。这是您接收有关连接是否已建立、数据接收方式以及连接已完成的信息的方式(connectiondFinishLoading)。更多信息请访问
因此,基本上,您放入连接的代码IDFinishLoading必须向视图控制器发送某种消息,以便它更新视图。您应该在启动nsurl连接的类中使用以下方法:
#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;
}
NSURLConnection *imageConnection
其中imageConnection是NSURLConnection类型的属性:
#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;
}
NSURLConnection *imageConnection
而activeDownload是一个NSMutableData:
NSMutableData *activeDownload
我不够具体,我已经实现了ConnectiondFinishLoading,并尝试了NSNotification向控制器发送通知,但从ConnectiondFinishLoading发送的通知在控制器中没有收到,可能是因为它在不同的线程中运行?我还能用什么?你是不是只是为了下载而使用线程?使用异步API会更容易。这样,您就可以通过普通的方法调用发送消息,比如
[controller imageDownloaded]
。在那里找到了我的解决方案。谢谢