【问题标题】:Check if an url string gives back a valid webpage.检查 url 字符串是否返回有效网页。
【发布时间】:2015-03-05 03:17:27
【问题描述】:

如何检查 image-url-string 是否返回有效的 url? 我说的是这个网址http://rscagen3t004-dev.tdlinx.dev/sites/all/themes/rsca/resources/images/RSCA_logo.png

当您单击该链接时,您可以看到该网页不可用。目前我正在我的代码中这样做:

 if([meta.met_thumb hasPrefix:@"http://"]){
                imgURL = meta.met_thumb;


                NSData *walImage = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imgURL]];
                NSLog(@"walImage is %@",walImage);
                float newHeight2;
                if (walImage != nil) {
                    UIImage *imgIcon = [UIImage imageWithData:walImage];
                    if (imgIcon != nil) {
                        float width = imgIcon.size.width;
                        float heigt = imgIcon.size.height;
                        if(heigt < 240){
                            float newWidth = (heigt / 240);
                            float newWidht2 = (newWidth/ width);
                            //[imgNews setFrame:CGRectMake(40,y, newWidht2,heigt)];
                        }
                        float newHeight =  (width / 240);
                        newHeight2 = heigt/ newHeight;
                    }else{
                        newHeight2 = 240;
                    }

                }else{
                    newHeight2 = 240;
                }


                height = [self heightForStatus:attString] + y + newHeight2 + 70;
            }else{
                height = [self heightForStatus:attString] + y + 240 + 70;
            }

但是执行[[NSData alloc] init]这一行需要很长时间。

谁能帮我解决这个问题?

提前致谢!

【问题讨论】:

  • “有效网址”是什么意思?在您的代码中,您不会测试 URL 是否有效,而是下载图像。
  • 就像您单击链接时看到的那样。它没有返回显示“网页不可用”的图像
  • 一个“有效”的 URL 并不意味着服务器可以响应,也不意味着响应速度很快。将代码放在后台。

标签: objective-c iphone uiimage nsdate nsurl


【解决方案1】:

alloc/init 行执行延迟时间长,可能是服务器响应慢造成的。我刚刚测试过,30 秒后我既没有得到图像也没有得到错误页面。

要检测“有效 URL”,您应该检查服务器响应。它应该给出 404 = not found 的正确响应。另见http响应代码http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

因此,您应该检查您是否收到 404 或相应的 2xx 响应。然后决定是否有数据并创建图像。不过,这可能会出错,例如,如果没有接收到图像数据而是一个网页。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-08-20
  • 2013-10-17
  • 2021-10-10
  • 2011-11-26
  • 1970-01-01
  • 2019-05-05
  • 2019-10-04
  • 1970-01-01
相关资源
最近更新 更多