Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> iOS

วิธีเปิดเว็บไซต์ในเบราว์เซอร์ Safari จากแอป iOS

เปิด URL ใน Safari (External Browser) จากแอป iOS

ใช้ UIApplication.shared.open(_:options:completionHandler:) เปิดลิงก์ในเบราว์เซอร์ระบบ

ขั้นตอนที่ 1: สร้างโปรเจกต์

Xcode → Single View App → ชื่อ "OpenBrowser"

ขั้นตอนที่ 2: เพิ่ม Button ใน Storyboard

ตั้ง Title "Open Facebook" สร้าง IBAction openBrowser

ขั้นตอนที่ 3: โค้ดเปิด URL

@IBAction func openBrowser(_ sender: Any) {
    guard let url = URL(string: "https://www.facebook.com") else { return }
    
    if UIApplication.shared.canOpenURL(url) {
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
    } else {
        print("Cannot open URL: \(url)")
        // Fallback หรือแสดง Alert
    }
}

คำอธิบาย

  • canOpenURL: เช็คว่าเครื่องมีแอปเปิด URL นี้ได้ไหม (เช่น มี Safari หรือไม่)
  • open(_:options:completionHandler:): เปิด URL ในแอปที่เหมาะสม (https → Safari)
  • options: สำหรับ Universal Links, หรือ [.universalLinksOnly: true]
  • completionHandler: Callback เมื่อเปิดสำเร็จ/ล้มเหลว

ขั้นตอนที่ 4: Info.plist - LSApplicationQueriesSchemes (สำคัญ!)

iOS 9+ ต้องประกาศ URL Schemes ที่จะเช็คด้วย canOpenURL

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>https</string>
    <string>http</string>
</array>

หรือเฉพาะ Scheme ที่ต้องการเช็ค (เช่น "fb", "twitter", "instagram")

รันทดสอบ

  1. กดปุ่ม "Open Facebook"
  2. Safari จะเปิดและโหลด facebook.com
  3. แอปของเราจะอยู่ใน Background

ขยายความสามารถ

Universal Links (เปิดในแอปถ้ามี, ไม่งั้น Safari)

UIApplication.shared.open(url, options: [.universalLinksOnly: true]) { success in
    if !success {
        // Fallback: เปิดใน Safari แทน
        UIApplication.shared.open(url)
    }
}

เปิดแอปเฉพาะ (Deep Link)

// เปิด Facebook App ถ้ามี, ไม่งั้นเว็บ
let fbURL = URL(string: "fb://profile/12345")!
let webURL = URL(string: "https://facebook.com/12345")!

if UIApplication.shared.canOpenURL(fbURL) {
    UIApplication.shared.open(fbURL)
} else {
    UIApplication.shared.open(webURL)
}

SafariViewController (In-App Browser)

หากไม่อยากออกจากแอป ใช้ SFSafariViewController:

import SafariServices

let svc = SFSafariViewController(url: url)
present(svc, animated: true)
  • ผู้ใช้อยู่ในแอปเราตลอด
  • Share Cookies กับ Safari
  • มี Done Button ปิดกลับมาได้