【问题标题】:How to call the func in ViewController from appdelegate in Swift?如何从 Swift 中的 appdelegate 调用 ViewController 中的函数?
【发布时间】:2015-10-13 16:02:00
【问题描述】:

我正在尝试在 Swift 中从 appdelegate 调用 ViewController 中的函数?

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) 时,它显示 Cannot invoke 'fileurl' with an argument list of type '(NSURL)'

当我调用 first.fileurl(url) 时,它崩溃并且错误日志是fatal error: unexpectedly found nil while unwrapping an Optional value

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

【问题讨论】:

  • 在日志中您是否看到任何显示此错误的变量名称?看起来该方法正在被调用,但 url 参数的值为 nil,并且由于强制展开而崩溃
  • is FirstViewController 是导航堆栈中的视图控制器还是可见控制器?
  • @developer 我已经打印了 url ,它不是零。
  • @Akhilrajtr 它是可见的控制器!
  • @Martin 尝试打印您的 first 对象,我猜它的 nil

标签: ios iphone func


【解决方案1】:

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

【讨论】:

  • 谢谢!这就是它立即为我工作的方式。
【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-04
    • 2015-04-13
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多