ios - 如何从 iOS AppDelegate 调用 View Controller 函数?

标签 ios swift apple-push-notifications

我收到了来自远程推送通知的调用,其中包括我想要显示的图像的路径。

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/

相关文章:

ios - 使用 Soom-La 从 Unity3D 跨平台 IAP

ios - 如何制作突出显示的自定义按钮

ios - 从 iOS 10.3 之前的 SecCertificate 获取 SecKey

swift - TokBox: 'consumeFrame' 在使用修改后的像素缓冲区时崩溃

iphone - 如何处理用户数据在不同时间到达的多个推送通知?

iPhone 推送通知信息

ios - 如何使用 NSURLIsExcludedFromBackupKey 或 kCFURLIsExcludedFromBackupKey?

android - 从现有后端创建 iOS 或 Android 应用程序

swift - 如何快速修剪字符串中的空格和空值?

grails - 生产iOS推送通知在本地发送,但不是从AWS Elastic beantalk发送