简体   繁体   中英

How to call the func in ViewController from appdelegate in Swift?

I am trying to call the function in ViewController from appdelegate in Swift?

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

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

In Appdelegate.swift , I call the FirstViewController.fileurl() and also try to call first.fileurl() .

When I call FirstViewController.fileurl(url) , it show Cannot invoke 'fileurl' with an argument list of type '(NSURL)' .

When I call first.fileurl(url) , it crash and the error log is fatal error: unexpectedly found nil while unwrapping an Optional value .

Did I missing something ? Thanks in advance.

It's your UIViewController called first that is not initialized. If this done in another place eg in storyboard during loading of your app, you only need to assign the rootviewcontroller to your variable. One way of doing this is:

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

Since your first object is nil you should first allocate a new object by using the below code :

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

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

You need to use your storyboard. Give identifier to your ViewController using storyboard.

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

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