如何从iOS AppDelegate调用视图控制器函数? [英] How can I call a view controller function from an iOS AppDelegate?
问题描述
我正在从远程推送通知中接到电话,该通知包括要显示的图像的路径.
I am getting a call from a remote push notification, which includes a path to an image, which I want to display.
AppDelegate是:
The AppDelegate is:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
// get url from notification payload (shortened version)
let url = alert["imgurl"] as? NSString
let vc = ViewController()
vc.loadImage(url as String) // cannot find the imageView inside
}
...视图如下:
func loadImage(url:String) {
downloadImage(url, imgView: self.poolImage)
}
// http://stackoverflow.com/a/28942299/1011227
func getDataFromUrl(url:String, completion: ((data: NSData?) -> Void)) {
NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: url)!) { (data, response, error) in
completion(data: NSData(data: data!))
}.resume()
}
func downloadImage(url:String, imgView:UIImageView){
getDataFromUrl(url) { data in
dispatch_async(dispatch_get_main_queue()) {
imgView.image = UIImage(data: data!)
}
}
}
我得到一个例外,说imgView
为空(它声明为@IBOutlet weak var poolImage: UIImageView!
,并且可以通过单击按钮调用loadImage("http://lorempixel.com/400/200/")
来显示图像.
I'm getting an exception saying imgView
is null (it is declared as @IBOutlet weak var poolImage: UIImageView!
and I can display an image by calling loadImage("http://lorempixel.com/400/200/")
from a button click.
我在stackoverflow上找到了两个相关的答案(上面提到了一个),但是没有用.
I found a couple of related answers on stackoverflow (one is referenced above) but none work.
推荐答案
如果要模态显示新的视图控制器,请进一步研究rach的答案.
If you want to show a new view controller modally, then look into rach's answer further.
如果您已经在屏幕上查看ViewController,则需要对其进行更新以显示所需的信息.
If you're ViewController is already on screen, you will need to update it to show the information you need.
如何执行此操作将取决于您的根视图控制器设置.您的视图控制器是否嵌入在UINavigationController中?如果是这样,请尝试以下操作:
How you do this will depend on your root view controller setup. Is your view controller embedded in an UINavigationController? If so then try this:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
if let rootViewController = window?.rootViewController as? UINavigationController {
if let viewController = rootViewController.viewControllers.first as? ViewController {
let url = alert["imgurl"] as? NSString
viewController.loadImage(url as String)
}
}
}
如果不是,请尝试以下操作:
If it is not, then try this:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
if let rootViewController = window?.rootViewController as? ViewController {
let url = alert["imgurl"] as? NSString
rootViewController.loadImage(url as String)
}
}
这篇关于如何从iOS AppDelegate调用视图控制器函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!