Safari View Controller iOS Tutorial

收藏待读

Safari View Controller iOS Tutorial

Prior to iOS 9 when the user needs to connect to a web page the URL is handed off to safari. forcing the user to exit out of your application. From iOS 9 and later the Safari View Controller can be used to provide a full web experience inside of your application. In this tutorial a webpage is displayed inside a Safari View Controller. This tutorial is made with Xcode 10 and built for iOS 12.

Open Xcode and create a new Single View App.

Safari View Controller iOS Tutorial

For product name, use IOSSafariViewControllerTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

Safari View Controller iOS Tutorial

Go to the Storyboard . Drag a Button from the Object Library to the main View. Double-click the button to change the title to “Open Web Page”. Select the “Resolve Auto Layout Issues” button on the bottom-right and choose “Add Missing Constraints”.

Safari View Controller iOS Tutorial

The Storyboard will look like this.

Safari View Controller iOS Tutorial

Open the Assistant Editor and make sure the ViewController.swift file is visible. Ctrl-drag from the Button in the Storyboard to the ViewController class of the ViewController.swift file to create the following Action.

Safari View Controller iOS Tutorial

At the top of the ViewController.swift file import the SafariServices framework.

import SafariServices

Implement the openURL(_:) Action method.

@IBAction func openURL(_ sender: Any) {
    // check if website exists
    guard let url = URL(string: "https://apple.com") else {
        return
    }

    let safariVC = SFSafariViewController(url: url)
    present(safariVC, animated: true, completion: nil)
}

To dismiss the Safari View Controller the View Controller needs to conform to the SFSafariViewControllerDelegate. Change the class declaration to

class ViewController: UIViewController, SFSafariViewControllerDelegate

Add the following delegate method

func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
    controller.dismiss(animated: true, completion: nil)
}

Finally add the following line to the openURL Action method

safariVC.delegate = self

Build an Runthe Project and click on the button to open the website. The Safari View Controller is displayed containing the Apple Web Site. Pressing the Done button will dismiss the Safari View Controller.

Safari View Controller iOS Tutorial

You can download the source code of the IOSSafariViewControllerTutorial at the ioscreator repository on Github .

原文 : iOScreator

相關閱讀

免责声明:本文内容来源于iOScreator,已注明原文出处和链接,文章观点不代表立场,如若侵犯到您的权益,或涉不实谣言,敬请向我们提出检举。