본문 바로가기
모바일/IOS

how to open an URL in Swift

by 죠부니 2018. 2. 23.
반응형

https://stackoverflow.com/questions/39546856/how-to-open-an-url-in-swift3


guard let url = URL(string: "http://www.google.com") else {
  return //be safe
}

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


Above answer is correct but if you want to check you canOpenUrl or not try like this.

let url = URL(string: "http://www.facebook.com")!
if UIApplication.shared.canOpenURL(url) {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
    //If you want handle the completion block than 
    UIApplication.shared.open(url, options: [:], completionHandler: { (success) in
         print("Open url : \(success)")
    })
}

Note: If you doesn't want to handle completion you can also write like this.

UIApplication.shared.open(url, options: [:])

No need to write completionHandler as of it contains default value nil, check apple documentation for more detail.



--

둘을 섞어보자

      let url = URL(string: "https://www.facebook.com/")!

        if UIApplication.shared.canOpenURL(url) {

            if #available(iOS 10.0, *) {

                UIApplication.shared.open(url, options: [:], completionHandler: nil)

            } else {

                UIApplication.shared.openURL(url)

            }

        }


반응형

'모바일 > IOS' 카테고리의 다른 글

공유하기 UIActivityViewController  (0) 2018.03.02
무한스크롤 infinite scroll  (0) 2018.02.27
키보드관련  (0) 2018.02.09
UIAlertController, UIAlertAction  (0) 2018.02.09
button에 이벤트 추가  (0) 2018.01.30