网页加载时间代码段仅适用于https网站

时间:2016-05-31 13:00:43

标签: ios loading webpage

以下为iOS应用程序编写的代码段(查找网页加载时间)仅适用于https网站。但是,当我尝试给http网站时,它显示网页加载错误。我应该改变哪部分代码?

self.setTextLabel.text = @"Loading...";
    NSURL *urlValue = [NSURL URLWithString:_textView.text];
    NSURLRequest *request= [NSURLRequest requestWithURL:urlValue];
    NSDate *start=[NSDate date];
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    /*NSURLSessionDataTask *task =[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response,NSError *error)
    {*/
    NSDate *end=[NSDate date];
        if(response != nil)
        {
            double ellapsedSeconds= [end timeIntervalSinceDate:start];
            self.setTextLabel.text = [NSString stringWithFormat:@"%f ", ellapsedSeconds];

        }
        else
        {
            self.setTextLabel.text = @"Web Page Loading error !";

        }

1 个答案:

答案 0 :(得分:1)

首先,您需要执行此操作:打开Info.plist,并添加以下行:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

1)如果你正在使用网页浏览,那么

//让我们说这是您加载请求的位置,并且您已经使用委托设置了您的webview

-(void)loadRequest{

      [webView loadRequest:yourRequest];
      startDate=[NSDate date];
   }

//这是UIWebView的委托回调

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
   NSDate *endDate=[NSDate date];
   double ellapsedSeconds= [endDate timeIntervalSinceDate:startDate];
}

2)没有webview:

 NSDate *start=[NSDate date];
    NSURLRequest *r= [[NSURLRequest alloc] initWithURL:url]; 
    NSData *response=   [NSURLConnection sendSynchronousRequest:r returningResponse:nil error:nil];
   NSDate *end=[NSDate date];
 double ellapsedSeconds= [start timeIntervalSinceDate:end];