YingYang
YingYang

Reputation: 418

IOS Swift: Load new url to a webview after receiving a push notification

I have a Swift 2.0 app with a webview and push notification. The Webview is working every time the app starts.

After receving a push notifications, i need to call another url. (to react on the push message)

How can I access the webview element in my appdelegate function didReceiveRemoteNotification ? Is this possible?

My Code so far:

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)
}

Delegate:

// 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)




}

Many Thanks.

Upvotes: 2

Views: 3498

Answers (1)

Hardik Shekhat
Hardik Shekhat

Reputation: 1878

By using NSNotificationCenter , you can do it.

First set notification and set selector in your 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)
}

When receive remote notification then post notification in didReceiveRemoteNotification method from AppDelegate Class.

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)
}

Upvotes: 6

Related Questions