我正在开发一个应用程序,我使用以下代码检查 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 一起工作,但仍在寻找更好的选择。