我正在开发一个应用程序,使用以下代码检查url。
-(无效)存在{NSString*strImg=@"某个url";NSURL*aImgUrl=[NSURL URLWithString:strImg];NSMutableURLRequest*imgRequest=[NSMutableURLRequest WithURL:strImg];[imgRequest setHTTPMethod:@"HEAD"];imgConnection=[NSURLConnection connectionWithRequest:imgRequest delegate:self];}
当我得到回应时,我会这样做。
-(void)连接:(NSURLConnection*)连接didReceiveResponse:(NSURLResponse*)响应{如果([(NSHTTPURLResponse*)response statusCode]==200){//url存在appDel.isExists=TRUE;temp=假;[自加载数据];NSLog(@"%ld",(long)[(NSHTTPURLRResponse*)response statusCode]);}否则,如果([(NSHTTPURLResponse*)response statusCode]==404){//url不存在appDel.isExists=FALSE;温度=真;[自加载数据];NSLog(@"%ld",(long)[(NSHTTPURLRResponse*)response statusCode]);}}
这是我的装载数据代码
-(void)loadData{结果=FALSE;isReqSent=FALSE;做{if(appDel.isExists==TRUE){NSURL*aTxtUrl=[NSURL URLWithString:apiText];NSURL*aImgUrl=[NSURL URLWithString:apiImage];NSURLRequest*imgRequest=[NSRRequest requestWithURL:aImgUrl];NSURLRequest*txtRequest=[NSRRequest requestWithURL:aTxtUrl];[NSRLConnection sendAsynchronousRequest:txt请求队列:[NSROperationQueue mainQueue]完成处理程序:^(NSURLResponse*响应,NSData*数据,NSError*连接错误){if(数据){NSString*strTxt=[[NSStringalloc]initWithData:数据编码:NSUTF8StringEncoding];[lblTime setText:strTxt];[policyImgWebView加载请求:imgRequest];结果=真;}}];}if(结果){appDel.isExists=TRUE;}其他的{if(!isReqSent){NSString*soapMessage=@"我的soap消息";NSString*soapAction=@"我的soap url";[objWebServiceParser xmlParsing:soapMessage:soapAction:Number];isReqSent=TRUE;}}if(temp){dispatch_async(dispatch_get_global_queue(dispatch_queue_PRIORITY_BROUNDATION,0)^{[自身背景过程];});}}而(结果==FALSE)
这是我的后台处理
-(void)backgroundProcess{NSString*strImg=@"某个url";NSURL*aImgUrl=[NSURL URLWithString:apiImage];NSMutableURLRequest*imgRequest=[NSMutableURLRequest请求WithURL:aImgUrl];[imgRequest setHTTPMethod:@"HEAD"];imgConnection=[NSURLConnection connectionWithRequest:imgRequest delegate:self];}
我不知道自己哪里做错了,有人能指引我吗?
我希望后台进程一直运行,直到它得到数据,当数据接收到appdel.isExists得到true&进入主线程以更新ui。
我试过GCD&CCD_ 1,但我没有把它做好&我得到CCD_ 2失败错误35。
它与NSURLSessionDownloadTask一起工作,但仍在寻找更好的选项。
不要在后台调用NSURLConnection
。由于NSURLConnection
将自动工作。由于您不发送异步请求,它将在后台工作,不会挂起您的主线程。在负载数据中删除调度。您有:
if (temp)
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
[self backgroundProcess];
});
}
成功:
if (temp)
{
[self backgroundProcess];
}
您不需要使用dispatch。
要从服务器加载UIImageView
中的图像,可以使用以下框架。
SDWebImage
得到completionBlock
、progressBlock
&您可以使用更多的属性来更新UI。它会分块通知你,然后你可以在UI上更新你想要的任何内容。
样本:
如果imageURL
是有效的(这是你的情况),只加载图像就和这个代码一样简单
UIImageView *imageView;
[imageView setImageWithURL:[NSURL URLWithString:YOUR_URL]];
它也有丰富的方法,比如下面的
UIImageView *imageView;
[imageView setImageWithURL:[NSURL URLWithString:YOUR_URL]
placeholderImage:[UIImage imageNamed:@"placeholder.png"]
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType)
{
// in "image" you'll get the downloaded image from the URL
... completion code here ...
}];