Siddharth
Siddharth

Reputation: 4312

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

Upvotes: 15

Views: 29897

Answers (3)

Elijah
Elijah

Reputation: 2213

I know this question is old and for iOS, but for macOS, there's two ways to do it.

// Constants.swift
enum URLs {
    static let MyURL = URL(string: "https://google.com")!
}

One way is the straightforward openURL

struct MyView: View {
    @Environment(\.openURL) private var openURL
...
.onTapGesture {
            self.openURL(URLs.MyURL)
        }
}

The second way is applicable when you are not in a view.

NSApp.delegate?.application?(NSApp, open: [URLs.MyURL])

Upvotes: 0

Abhishek Thapliyal
Abhishek Thapliyal

Reputation: 3708

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)
}

Upvotes: 25

Pooja Singh
Pooja Singh

Reputation: 136

Please try this.

if let url = URL(string: urlString), UIApplication.shared.canOpenURL(url) {
   if #available(iOS 10.0, *) {
      UIApplication.shared.open(url, options: [:], completionHandler: nil)
   } else {                                            
      UIApplication.shared.openURL(url)
   }
}

Upvotes: 6

Related Questions