XCode 7 - Swift - 通过SFSafariViewController自动加载站点

时间:2015-11-19 16:59:54

标签: ios xcode

我正在更新我们的iTunes应用程序,并希望利用新的SFSafariViewController api。用例非常简单,当用户打开应用程序时,应用程序会自动在SFSafariViewController中加载设置的URL。

这方面的教程似乎有限,而且确实存在的教程在应用程序打开后通过链接涉及IBActions。

当用户点击其设备上的应用时,如何在SFSafariViewController中自动打开链接?

以下代码只是白页:

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.
    }
}

----工作守则----

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)
    }
}

1 个答案:

答案 0 :(得分:2)

您当前的代码正在尝试显示ViewController中的当前视图控制器(SFSafariViewController),该控制器甚至尚未显示。

尝试交换此内容:

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

为此:

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