NSURLConnection sendAsynchronousRequest 在某些刷新请求上没有命中完成处理程序
Posted
技术标签:
【中文标题】NSURLConnection sendAsynchronousRequest 在某些刷新请求上没有命中完成处理程序【英文标题】:NSURLConnection sendAsynchronousRequest does not hit completion handler on some refresh requests 【发布时间】:2013-06-11 02:27:48 【问题描述】:我有这个代码块:
+(void)requestPath:(NSString *)path onCompletion:(RequestCompletionHandler)complete
// Background Queue
NSOperationQueue *backgroundQueue = [[NSOperationQueue alloc] init];
// URL Request
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:path]
cachePolicy:NSURLCacheStorageAllowedInMemoryOnly
timeoutInterval:10];
// Send Request
[NSURLConnection sendAsynchronousRequest:request
queue:backgroundQueue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (complete) complete(result,error);
];
此代码在我使用它的 99% 的时间里都可以毫无问题地为我的应用提取数据。但是,有时(但并非总是)在 UIRefreshControl 刷新请求上,NSURLConnection sendAsynchronousRequest 中的完成处理程序未命中,这会导致我的应用程序崩溃。
我可能会请求相同的数据,有时完成处理程序会被命中,但其他时候刷新它将不起作用。
我不确定为什么会这样。
任何帮助将不胜感激。
谢谢!
【问题讨论】:
【参考方案1】:正确处理错误情况
[NSURLConnection sendAsynchronousRequest:request
queue:backgroundQueue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
if (error)
NSLog(@"%@",[error localizedDescription]);
else
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//if (complete) complete(result,error);
];
【讨论】:
以上是关于NSURLConnection sendAsynchronousRequest 在某些刷新请求上没有命中完成处理程序的主要内容,如果未能解决你的问题,请参考以下文章
HttpClient.SendAsync() 未将 JSON 作为字符串发送
模拟 HttpClient.SendAsync 以返回内容不为空的响应