chaneeii / iOS-Study-Log

✨ iOS에 대해 공부한 것들을 기록합니다 ✨
19 stars 0 forks source link

앱에서 외부url을 여는 법 / 옵셔널 에러 해결 🐯 #47

Open chaneeii opened 1 year ago

chaneeii commented 1 year ago

방법1 : SafariServices 이용하기

아래 사진에서 볼 수 있듯, 이 방법을 사용하면 앱 내에서 웹뷰를 띄워주는 느낌

import SafariServices
if let url = URL(string: "https://www.google.com/") {
  let safariView: SFSafariViewController = SFSafariViewController(url: url)
  self.present(safariView, animated: true, completion: nil)
}

방법2 : UIApplication.shared.open() 이용하기

사파리 앱으로 연결

if let url = URL(string: "https://google.com") {
    UIApplication.shared.open(url, options: [:])
}
chaneeii commented 1 year ago

옵셔널 : 에러해결팁

카카오 api 웹으로 링크를 열려고 했더니 자꾸 아래와 같은 에러가 발생했다

"https://map.kakao.com/link/to/\(place.name),\(place.lat),\(place.lan)"
스크린샷 2022-10-13 오전 12 06 34

왜 옵셔널인거지? -> 바로 바로 한국어가 있었기 때문!

인코딩 해주니 잘 작동한다!

그래서 util 로 하나 빼서 만들었다

    static func openExternalLink(urlStr: String, _ handler:(() -> Void)? = nil) {

        // 인코딩 -> 한글, 특수 문자 등 처리
        let encoded = urlStr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""

        guard let url = URL(string: encoded) else {
            return
        }

        if #available(iOS 10.0, *) {
            UIApplication.shared.open(url, options: [:]) { _ in
                handler?()
            }

        } else {
            UIApplication.shared.openURL(url)
            handler?()
        }
    }

https://hongssup.tistory.com/218 https://sunidev.tistory.com/18