IOS Swift:收到推送通知后,将新网址加载到webview

时间:2015-09-23 11:34:35

标签: ios objective-c iphone swift webview

我有一个带有webview和推送通知的Swift 2.0应用程序。 每次应用程序启动时,Webview都在工作。

收到推送通知后,我需要拨打另一个网址。 (对推送消息作出反应)

如何在appdelegate函数didReceiveRemoteNotification中访问webview元素?这可能吗?

我的代码到目前为止:

ViewController:
class ViewController: UIViewController,UIWebViewDelegate { 
@IBOutlet var containerView: UIView!
@IBOutlet var webView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()
    self.webView.delegate = self;

        var urlStringHost = "http://www.exampleUrl.com"

        let url = NSURL(string: urlStringHost)

        let request = NSMutableURLRequest(URL: url!)
        request.HTTPMethod = "POST"

        webView.loadRequest(request)
}

代表:

// Push Empfangen
func application(application: UIApplication, didReceiveRemoteNotification userInfo:[NSObject : AnyObject]) {
    print("push empfangen")
    print(userInfo)
    application.applicationIconBadgeNumber = 0


    // Load some new url to the existing webview (not working)
    //webview?.loadRequest(request)




}

非常感谢。

1 个答案:

答案 0 :(得分:6)

通过使用NSNotificationCenter,您可以执行此操作。

首先在viewcontroller中设置通知和设置选择器。

func viewDidLoad() 
{
    super.viewDidLoad()

    //add observer for load request in webview when receive remote notification.
    NSNotificationCenter.defaultCenter().addObserver(self, selector:"PushReceiver:", name: "PushReceived", object: nil)
}

//When post notification then below method is called.
func PushReceiver(notifi: NSNotification) 
{
    var dicNotifi: [NSObject : AnyObject] = notifi.userInfo
    NSLog("notificiation Info %@ \n", dicNotifi)
}

接收远程通知后,在AppDelegate Class的didReceiveRemoteNotification方法中发布通知。

func application(application: UIApplication, didReceiveRemoteNotification userInfo:[NSObject : AnyObject]) 
{
    print("push empfangen")
    print(userInfo)
    application.applicationIconBadgeNumber = 0

    //post notification.
     NSNotificationCenter.defaultCenter().postNotificationName("PushReceived", object: nil, userInfo: userInfo)
}