如何从Swift中的appdelegate调用ViewController中的func?

时间:2015-07-23 11:18:51

标签: ios iphone func

我试图在Swift中ViewController调用appdelegate中的函数?

Appdelegate.swift

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var first: FirstViewController!

    func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {

        FirstViewController.fileurl(url)
        first.fileurl(url)
        return true
    }
}

FirstViewController.swift

import UIKit
class FirstViewController: UIViewController {
    var externalFile: NSURL!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    func fileurl(url: NSURL){
        externalFile = url
        println("externalFile = \(externalFile)")
}
}

Appdelegate.swift,我致电FirstViewController.fileurl()并尝试拨打first.fileurl()

当我致电FirstViewController.fileurl(url)时,它显示无法使用类型为'(NSURL)'的参数列表调用'fileurl'。

当我致电first.fileurl(url)时,它崩溃并且错误日志致命错误:在展开“可选”值时意外发现nil

我错过了什么吗?提前谢谢。

3 个答案:

答案 0 :(得分:2)

您的UIViewController名为first未初始化。如果这在另一个地方完成,例如在加载应用程序的故事板中,您只需要将rootviewcontroller分配给您的变量。一种方法是:

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var first: COBezierDemoViewController?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        if let firstViewController = self.window?.rootViewController as? COBezierDemoViewController {
            self.first = firstViewController
        }

        return true
    }

    func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {
        first?.fileurl(url)
    }
}

答案 1 :(得分:1)

由于您的first对象为nil,您应首先使用以下代码分配新对象

func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {

        let first = FirstViewController()
        first.fileurl(url)
        return true
    }

答案 2 :(得分:0)

您需要使用故事板。使用故事板为ViewController提供标识符。

let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = mainStoryboard.instantiateViewControllerWithIdentifier("<Controller ID>") as FirstViewController
vc.fileurl(url)