简体   繁体   中英

XCode 7 - Swift - Automatically load site via SFSafariViewController

I'm in the process of updating our iTunes app, and would like to take advantage of the new SFSafariViewController api. The use case is extremely simple, when user opens app, the app automatically loads the set url in a SFSafariViewController.

There seem to be limited tutorials on this, and the ones that do exist involve IBActions via links once the app is open.

How do I automatically open a link in SFSafariViewController when user clicks the app on the their device?

The following code just white pages:

import UIKit
import SafariServices

class ViewController: UIViewController
{
    private var urlString:String = "https://example.com"

    override func viewDidLoad()
    {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let svc = SFSafariViewController(URL: NSURL(string: self.urlString)!)

        svc.presentViewController(self, animated: true, completion: nil)
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

----Working Code----

import UIKit
import SafariServices

class ViewController: UIViewController
{
    private var urlString:String = "https://example.com"

    override func viewDidLoad()
    {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewDidAppear(animated: Bool) {

        super.viewDidAppear(animated)

        let svc = SFSafariViewController(URL: NSURL(string: self.urlString)!)

        self.presentViewController(svc, animated: true, completion: nil)
    }
}

Your current code is trying to present the current view controller ( ViewController ) from the SFSafariViewController , which isn't even being displayed yet.

Try swapping this:

svc.presentViewController(self, animated: true, completion: nil)

For this:

self.presentViewController(svc, animated: true, completion: nil)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM