Check if an URL has got http:// prefix

后端 未结 8 766
野的像风
野的像风 2021-02-07 08:45


In my application, when the user add an object, can also add a link for this object and then the link can be opened in a webView.
I tried to save a link without http://

8条回答
  •  鱼传尺愫
    2021-02-07 09:12

    Better to use the scheme property on the URL object:

    extension URL {
        var isHTTPScheme: Bool {
            return scheme?.lowercased().contains("http") == true // or hasPrefix
        }
    }
    

    Example usage:

    let myURL = URL(string: "https://stackoverflow.com/a/48835119/1032372")!
    if myURL.isHTTPScheme {
        // handle, e.g. open in-app browser:            
        present(SFSafariViewController(url: url), animated: true)
    } else if UIApplication.shared.canOpenURL(myURL) {
        UIApplication.shared.openURL(myURL)
    }
    

提交回复
热议问题