将String值转换为URL值

时间:2018-04-07 16:13:12

标签: ios swift uiwebview

在与斯威夫特的一些概念混淆之后,我正在重做我的颂歌。请记住我对swift的新意见。

在我的项目中,目前有2 ViewControllers,第一个有UITextFieldUIButton。在第二个中有一个UIWebView

我知道UIWebView只允许一个URL类型地址,所以我希望UITextField中引入的文本是一个URL,那么我该如何更改引入到URL中的字符串并显示UIWebView中的那个值(引入了网址)?我应该将该值存储在全局变量中吗?我真的尝试了所有......

3 个答案:

答案 0 :(得分:0)

您可以通过Segue将其发送到nextVC,或将其存储在默认值中并在那里阅读

let myUrl = URL(string:textfield.text)
self.performSegue(withIdentifier: "goToNext", sender:myUrl)

//

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if let let next =  segue.destination as?  nextVC {

      next.currentUrl = sender as! URL

    }

}

//

class nextVC : UIViewController
{
    var currentUrl:URL?
}

答案 1 :(得分:0)

检查用户是否输入了有效的网址非常重要。您可以在从URL加载请求时在第二个viewController中检查它 以下是整体代码:

第一个viewController:

var url: String!  
url = URL(string:textfield.text)    // Convert text to url
self.performSegue(withIdentifier: "yourIdentifier", sender:url)    // Go from one VC to other. 



override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let let vc =  segue.destination as?  nextVC {
      vc.url = self.url

    }
} 

第二个viewController:

var url: String!    // Global var  

if url.isUrl
{  
    webView.loadRequest(URLRequest(url: url!))
}  
else
{
    print("invalid url")
}

验证网址字符串扩展名

extension String {

    var isUrl: Bool {

        // for http://regexr.com checking
        // (?:(?:https?|ftp):\/\/)(?:xn--)?(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[#-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?

        let schemes = URLSchemes.getAllSchemes(separetedBy: "|").replacingOccurrences(of: "://", with: "")
        let regex = "(?:(?:\(schemes)):\\/\\/)(?:xn--)?(?:\\S+(?::\\S*)?@)?(?:(?!10(?:\\.\\d{1,3}){3})(?!127(?:\\.\\d{1,3}){3})(?!169\\.254(?:\\.\\d{1,3}){2})(?!192\\.168(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[#-z\\u00a1-\\uffff]{2,})))(?::\\d{2,5})?(?:\\/[^\\s]*)?"


        let regularExpression = try! NSRegularExpression(pattern: regex, options: [])
        let range = NSRange(location: 0, length: self.characters.count)
        let matches = regularExpression.matches(in: self, options: [], range: range)
        for match in matches {
            if range.location == match.range.location && range.length == match.range.length {
                return true
            }
        }
        return false
    }

    var toURL: URL? {

        let urlChecker: (String)->(URL?) = { url_string in
            if url_string.isUrl, let url = URL(string: url_string) {
                return url
            }
            return nil
        }

        if !contains(".") {
            return nil
        }

        if let url = urlChecker(self) {
            return url
        }

        let scheme = URLSchemes.detectScheme(urlString: self)
        if scheme == .unknown {
            let newEncodedString = URLSchemes.http.rawValue + self
            if let url = urlChecker(newEncodedString) {
                return url
            }
        }

        return nil
    }
}

答案 2 :(得分:0)

Here is an example of how to do this.

这是要点:

的ViewController:

class ViewController: UIViewController, UIWebViewDelegate {

    @IBOutlet weak var urlTextView: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let webViewController = segue.destination as? WebViewController {
            if let url = sender as? URL {
                webViewController.urlToLoad = url
            }
        }
    }

    @IBAction func gotoURLButtonAction(_ sender: Any) {
        let url = self.urlTextView.text ?? ""
        if url.count > 0 {
            if isProperHTTPUrl(str: url) {
                self.performSegue(withIdentifier: "ViewControllerToWebViewController", sender: URL(string: url))
            } else {
                showError("not proper url format")
            }
        } else {
            showError("must set url")
        }
    }

    func isProperHTTPUrl(str:String) -> Bool {
        let re = try! NSRegularExpression(pattern: "(?i)https?:\\/.*", options: [])
        return re.numberOfMatches(in: str, options: .anchored, range: NSRange(location: 0, length: str.count)) > 0
    }
}

WebViewController:

class WebViewController: UIViewController {
    var urlToLoad:URL?
    @IBOutlet weak var webView: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let url = self.urlToLoad {
            self.webView.loadRequest(URLRequest(url: url))
        }
    }

    public func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        showError("Unable to load, \(error)")
    }
}