NSMutableURLRequest 异步回调的问题

tqwboy 2014-08-04 06:30:27
最近由Android转到IOS开发,在用NSMutableURLRequest做一个异步下载文件的功能模块,在这里遇到一些线程的问题,百度很久,也没找到很清晰的资料,所以特来请教。

在使用NSMutableURLRequest做异步请求的时候,在整个过程中会触发以下几个回调:
- (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

这些回调在被调用的时候,是处于子线程中呢,还是在主线程?

此外,我调用NSURLConnection的cancel方法的时候,会触发哪些回调?
...全文
170 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
ReyZhang 2014-08-05
  • 打赏
  • 举报
回复
1.回调方法是在主线程上执行。可想而知,有时我们需要在回调方法中修改页面UI. 修改UI只能是在主线程中处理 2. 发送cancel消息不会调用任何的代理的方法。看一下下面的伪代码
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
    NSInteger status = [(NSHTTPURLResponse *)response statusCode]; 
    
    if (status != 200) 
        [self cancel:connection]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
       /////// to do your logic
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 
    [self cancel:connection]; 
} 


- (void)cancel:(NSURLConnection *)connection { 
    [connection cancel]; 
    /////////to do your logic.
}
看苹果文档的解释 After this method is called, the connection makes no further delegate method calls. If you want to reattempt the connection, you should create a new connection object.
Bannings 2014-08-04
  • 打赏
  • 举报
回复
1.你收到这些回调的时候,在主线程,你可以通过这种方式得到主线程:[NSThread mainThread] 2.调用cancel会回调didFailWithError,前提是你不是在delegate回调里调用的cancel。如didReceiveData这个回调方法,你如果在这个方法里调用cancel的话,则不会调用didFailWithError

29,049

社区成员

发帖
与我相关
我的任务
社区描述
主要讨论与iOS相关的软件和技术
社区管理员
  • iOS
  • 大熊猫侯佩
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧