iosiphoneswiftswift2

Open web url link in browser in Swift


I want to load webpage that link I fetched through web service. I have tried myself but result is not in favour.

From server I was getting this kind of url: http://www.simrishamn.se/sv/kultur_fritid/osterlens_museum/

Also I have used this type of code to load the page:

let url = URL(string: "http://" + urlSting.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!)
UIApplication.shared.openURL(url!)

But when I test this code in device, its showing like this:

enter image description here

Please give some help to load fetched web url.

EDIT: After doing suggested changes, not web browser not opening though button click event is working, check below image for more clearance:

enter image description here


Solution

  • You need to check

    like this

    if let url = URL(string: urlSting.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!), UIApplication.shared.canOpenURL(url) {
        UIApplication.shared.open(url)
    }
    

    Also try removing and/or adding https:// prefix,
    and if does not work then simply do:

    if let url = URL(string: urlSting), UIApplication.shared.canOpenURL(url) {
        UIApplication.shared.open(url)
    }