gpt4 book ai didi

swift - 检查加载的 WebView 的 URL

转载 作者:行者123 更新时间:2023-11-30 10:19:24 24 4
gpt4 key购买 nike

我正在尝试检查网址是否有效,但我的 DNS 对所有内容都返回 200。因此,我想加载一个网址,而不将其加载到将显示的实际 Web View 中,然后检查请求网址。

这就是我所拥有的,但它总是返回 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 而不将其加载到 Storyboard 中的实际 View 中,以便我可以检查 finishNavigation url 是什么?

最佳答案

您可以使用此扩展:

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

关于swift - 检查加载的 WebView 的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28006658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com