我收到了来自远程推送通知的调用,其中包括我想要显示的图像的路径。
AppDelegate 是:
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
}
... View 如下所示:
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/")
从按钮点击。
我在 stackoverflow 上找到了几个相关的答案(上面引用了一个),但都没有用。
最佳答案
如果您想以模态方式显示新的 View Controller ,请进一步查看 rach 的答案。
如果您的 ViewController 已经在屏幕上,您将需要更新它以显示您需要的信息。
如何执行此操作取决于您的 Root View Controller 设置。您的 View Controller 是否嵌入到 UINavigationController 中?如果是这样,那么试试这个:
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)
}
}
}
如果不是,那么试试这个:
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 - 如何从 iOS AppDelegate 调用 View Controller 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36407437/