【发布时间】:2014-03-27 18:18:50
【问题描述】:
我正在开发一个应用程序,我使用以下代码检查 url。
-(无效)存在 { NSString *strImg = @"一些网址"; NSURL *aImgUrl = [NSURL URLWithString:strImg]; NSMutableURLRequest *imgRequest = [NSMutableURLRequest requestWithURL:strImg]; [imgRequest setHTTPMethod:@"HEAD"]; imgConnection = [NSURLConnection connectionWithRequest:imgRequest delegate:self]; }当我得到回复时,我会这样做。
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { if ([(NSHTTPURLResponse *)response statusCode] == 200) { // 网址存在 appDel.isExists = TRUE; 温度=假; [自加载数据]; NSLog(@"%ld",(long)[(NSHTTPURLResponse *)response statusCode]); } 否则如果([(NSHTTPURLResponse*)响应状态码] == 404) { //url不存在 appDel.isExists = FALSE; 温度=真; [自加载数据]; NSLog(@"%ld",(long)[(NSHTTPURLResponse *)response statusCode]); } }这是我的加载数据代码
-(无效)加载数据 { 结果=假; isReqSent = 假; 做 { 如果(appDel.isExists == TRUE) { NSURL *aTxtUrl = [NSURL URLWithString:apiText]; NSURL *aImgUrl = [NSURL URLWithString:apiImage]; NSURLRequest *imgRequest = [NSURLRequest requestWithURL:aImgUrl]; NSURLRequest *txtRequest = [NSURLRequest requestWithURL:aTxtUrl]; [NSURLConnection sendAsynchronousRequest:txtRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { 如果(数据) { NSString *strTxt = [[NSString alloc]initWithData:数据编码:NSUTF8StringEncoding]; [lblTime setText:strTxt]; [policyImgWebView loadRequest:imgRequest]; 结果=真; } }]; } 如果(结果) { appDel.isExists = TRUE; } 别的 { 如果(!isReqSent) { NSString *soapMessage = @"我的肥皂信息"; NSString *soapAction = @"我的肥皂网址"; [objWebServiceParser xmlParsing:soapMessage:soapAction:Number]; isReqSent = TRUE; } } 如果(温度) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ [自背景进程]; }); } } 而(结果 == FALSE);这是我的后台进程
-(void)backgroundProcess { NSString *strImg = @"一些网址"; NSURL *aImgUrl = [NSURL URLWithString:apiImage]; NSMutableURLRequest *imgRequest = [NSMutableURLRequest requestWithURL:aImgUrl]; [imgRequest setHTTPMethod:@"HEAD"]; imgConnection = [NSURLConnection connectionWithRequest:imgRequest delegate:self]; }我不知道我哪里做错了,谁能指导我?
我希望后台进程继续运行,直到它获取数据,当接收到的数据 appdel.isExists 为真并进入主线程以更新 ui。
我尝试了 GCD 和 performSelectorInTheBackground,但我没有做对,我得到 NSThread 失败错误 35。
它与 NSURLSessionDownloadTask 一起工作,但仍在寻找更好的选择。
【问题讨论】:
-
你的意思是 performSelectorInTheBackground ?
-
是的,当我处理到后台时,我在 NSURLConnection 委托方法中没有得到响应。
-
您只想从 URL 加载图像吗?
-
是的@AkshitZaveri,但在后台(继续检查直到 url 有效,一旦有效加载它)
标签: ios objective-c nsxmlparser nsthread nsurlconnectiondelegate