检查已加载WebView的URL

时间:2015-01-18 02:44:49

标签: swift

我试图检查网址是否有效,但我的DNS为所有内容返回200。所以我想加载一个网址而不加载到一个实际的网页视图中,然后查看请求网址。

这就是我所拥有的,但它总是返回200.

    let url = NSURL(string: inSecureUrl)!
    var response: NSURLResponse?
    var request = NSURLRequest(URL: url)
    var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &urlErrors) as NSData?
    if let pHttpResponse = response as? NSHTTPURLResponse {
        isValidUrl = true

        println("valid url. Response: \(response)")
    } else {
        println("url error: \(urlErrors)")
    }

如果没有将didFinishNavigation加载到故事板中的实际视图中,我该怎么办?所以我可以查看finishNavigation网址是什么?

1 个答案:

答案 0 :(得分:1)

您可以使用此扩展程序:

import Foundation
import UIKit

extension NSURL
{
  struct ValidationQueue {
    static var queue = NSOperationQueue()
  }

  class func validateUrl(urlString: String?, completion:(success: Bool, urlString: String? , error: NSString) -> Void)
  {
    // Description: This function will validate the format of a URL, re-format if necessary, then attempt to make a header request to verify the URL actually exists and responds.
    // Return Value: This function has no return value but uses a closure to send the response to the caller.

    var formattedUrlString : String?

    // Ignore Nils & Empty Strings
    if (urlString == nil || urlString == "")
    {
      completion(success: false, urlString: nil, error: "URL String was empty")
      return
    }

    // Ignore prefixes (including partials)
    let prefixes = ["http://www.", "https://www.", "www."]
    for prefix in prefixes
    {
      if ((prefix.rangeOfString(urlString!, options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil)) != nil){
        completion(success: false, urlString: nil, error: "Url String was prefix only")
        return
      }
    }

    // Ignore URLs with spaces 
    let range = urlString!.rangeOfCharacterFromSet(NSCharacterSet.whitespaceCharacterSet())
    if let test = range {
      completion(success: false, urlString: nil, error: "Url String cannot contain whitespaces")
      return
    }

    // Check that URL already contains required 'http://' or 'https://', prepend if it does not
    formattedUrlString = urlString
    if (!formattedUrlString!.hasPrefix("http://") && !formattedUrlString!.hasPrefix("https://"))
    {
      formattedUrlString = "http://"+urlString!
    }

    // Check that an NSURL can actually be created with the formatted string
    if let validatedUrl = NSURL(string: formattedUrlString!)
    {
      // Test that URL actually exists by sending a URL request that returns only the header response
      var request = NSMutableURLRequest(URL: validatedUrl)
      request.HTTPMethod = "HEAD"
      ValidationQueue.queue.cancelAllOperations()

      NSURLConnection.sendAsynchronousRequest(request, queue: ValidationQueue.queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
        let url = request.URL!.absoluteString

        // URL failed - No Response
        if (error != nil)
        {
          completion(success: false, urlString: url, error: "The url: \(url) received no response")
          return
        }

        // URL Responded - Check Status Code
        if let urlResponse = response as? NSHTTPURLResponse
        {
          if ((urlResponse.statusCode >= 200 && urlResponse.statusCode < 400) || urlResponse.statusCode == 405)// 200-399 = Valid Responses, 405 = Valid Response (Weird Response on some valid URLs)
          {
            completion(success: true, urlString: url, error: "The url: \(url) is valid!")
            return
          }
          else // Error
          {
            completion(success: false, urlString: url, error: "The url: \(url) received a \(urlResponse.statusCode) response")
            return
          }
        }
      })
    }
  }
}

完整项目WKWebView示例:https://github.com/ericcgu/EGWKWebBrowser