2015-09-23 28 views
1

我有一個帶有webview和推送通知的Swift 2.0應用程序。 每當應用程序啓動時,Webview都在運行。IOS Swift:在收到推送通知後將新網址加載到webview

收到推送通知後,我需要調用另一個URL。 (對推送消息作出反應)

如何在我的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) 




} 

非常感謝。

回答

4

通過使用NSNotificationCenter,您可以做到這一點。

首先在您的視圖控制器中設置通知和設置選擇器。

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類的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) 
} 
+0

你好,這正是我正在尋找的。所以我可以在解決方案中的控制器中的推事件後處理請求,而不是在委託中。太棒了。非常感謝。 – YingYang

+0

如果我的答案對你有幫助,那麼請考慮將答案標爲正確,以便其他人可以快速找到答案。 –

+0

我做過了,但是它的唯一有效當我達到了15的聲望。(我在這裏是新的) – YingYang