How to open a url when clicking on Push Notifications in swift 2?

14,511

Add this to your didFinishLaunchWithOptions:

   //handel push note if app is closed
    //Sends it to the regular handler for push notifcaiton
    //didrecivepushnotificaiton
    if let remoteNotification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? NSDictionary
    {
        self.application(application, didReceiveRemoteNotification: remoteNotification as [NSObject : AnyObject])
    }


    if launchOptions != nil
    {
        print(launchOptions)
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewControllerWithIdentifier(myPage)
        window?.rootViewController = vc
    }

Where myPage is a string and it is the Tag/Storyboardid of the view you want to open that has a web view init.

And then add this method like this

func application( application: UIApplication,
                  didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {

    if var alertDict = userInfo["aps"] as? Dictionary<String, String> {
        let url = alertDict["url"]!
        //store the url for the push control view
        loginInformation.setObject(url, forKey: "URL")
        self.loginInformation.synchronize()

    }else{print("No go")}
    application.applicationIconBadgeNumber = 0
    //post notification.
    NSNotificationCenter.defaultCenter().postNotificationName("PushReceived", object: nil, userInfo: userInfo)

}

Where loginInformation is a NSDefault thingy. Then in the web view you have in the view controller that you linked up earlier you can pass the store value of the url you want into the variable for the url for the web view. You might have to tinker with this a bit for it to work. But this does work. Just needs a bit of set up

This will work when you pass this json to the system. This is exactly how I am doing it.

[aps: {
alert = "Hello from APNs Tester.";
badge = 1;
url = "http://www.google.com";
}]

Hope this helps

And here is the viewcontrller class that you need to use

class PushNotificationController: UIViewController {

var defualtUrl : String = "http://[email protected]"
var storedUrl : String = ""
var useUrl : String = ""
let loginInformation = NSUserDefaults.standardUserDefaults()

override func viewDidLoad() {
    super.viewDidLoad()

    //add observer for load request in webview when receive remote notification.
    NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(PushNotificationController.PushReceiver(_:)), name: "PushReceived", object: nil)
    /*
    if let alertDict = userInfo["aps"] as? Dictionary<String, String> {
        print("URL :", alertDict["url"]!)
    }else{print("No go")}
    */

    if loginInformation.objectForKey("URL") != nil
    {
        storedUrl = loginInformation.objectForKey("URL") as! String
        print("Stored url: " + storedUrl )
        if storedUrl.isEmpty
        {
            useUrl = defualtUrl
        }else{
            useUrl = storedUrl
        }
    }else
    {
        useUrl = defualtUrl
    }


    print("URL Using: " + useUrl)
    let myUrl = NSURL (string: useUrl);
    let requestObj = NSURLRequest(URL: myUrl!);
    pushNotePlayer.loadRequest(requestObj)

    //after it is loaded reset it to the defualt url if there is no other thing next time
    loginInformation.setObject(defualtUrl, forKey: "URL")
    self.loginInformation.synchronize()

}
@IBOutlet weak var pushNotePlayer: UIWebView!

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

}
Share:
14,511
S.D
Author by

S.D

Updated on June 04, 2022

Comments

  • S.D
    S.D almost 2 years

    I am actually using Amazon Web Services SNS to send push notifications in my IOS application. When clicking on the push notification while the application is running in the background the url(sent by the push notification) is open correctly in the WebView(WKWebView). The only issue I am getting is that, the url does not open in the WebView when the application is closed. How can I solve this issue?

    Here is the following code:

    App Delegate:

    func application(application: UIApplication,didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    
           UIApplication.sharedApplication().applicationIconBadgeNumber = 0
    
           NSNotificationCenter.defaultCenter().postNotificationName("ReceivedPushNotification", object: userInfo)
    
    }
    

    ViewController:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.receivedUrlFromPushNotification(_:)), name: "ReceivedPushNotification", object: nil)
    
    }
    
    func receivedUrlFromPushNotification(notification: NSNotification){
    
        let JSONData = notification.object!["aps"] as! NSDictionary
        let dictionary: NSDictionary = JSONData
        let v = dictionary.allValues[2] as! String
        let url = "http://\(v)"
        self.webView!.loadRequest(NSURLRequest(URL: NSURL(string:url)!))
    }
    

    JSON code send in the push notification:

    {
    "APNS_SANDBOX":"{\"aps\":{\"alert\":\"test\",\"badge\":1,\"sound\":\"default\",\"url\":\"www.example_samplelink.com\"}}"
    }