Anand Yadav
Anand Yadav

Reputation: 489

Multiple ios push notification causes causes app to crash. Terminated due to signal 6(SIGABRT)

enter image description hereThese are image's before and after the app crashes,the console only show message Message from debugger: Terminated due to signal 6 enter image description here[[![My app launches (when not running) successfully from push notification and also i get the desired screen and result, but crashes when it receive's notification again from tap of notification while the app is active. When the app is launched normally from home screen notification function and action work fine in both while is app active and in background.I am posting my code below please help me.

When I'm launching my application from the notification received, app lunches successfully and goto respected window,now again when i receive notification while app is open then app crashes, means whenever my app is not running in background or foreground and i launch my app using notification.. and then again when i receive notification app crashes

My Code is below please help

import UIKit

@UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.

    let barAppearace = UIBarButtonItem.appearance()
    barAppearace.setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -60), forBarMetrics:UIBarMetrics.Default)  //CODE TO REMOVETITLE OFACK BUTTON ITEM IN NAVIGATIION CONTROLLER


    let notificationTypes : UIUserNotificationType = [.Alert, .Badge, .Sound]
    let notificationSettings : UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)
    UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)




    if let notification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? [String: AnyObject] {


         NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AgentAllTab.readyNotificationAction), name: "AgentReadyNotification", object: nil)
        let userInfo = launchOptions![UIApplicationLaunchOptionsRemoteNotificationKey] as? [String: AnyObject]

        let aps = userInfo!["aps"] as! [String: AnyObject]
        print("Remote noti data from didFinishLaunchingWithOptions \(aps)")

        let data = aps["data"]  as! [String: AnyObject]
        let type = aps["type"] as! Int
        print("notification TYPE  \(type)")

switch type { case 0 :

            NSUserDefaults.standardUserDefaults().setObject(aps, forKey: "notificationlauch")

        break
       default:
       break


}

return true

}

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings)
    {
         if notificationSettings.types != .None {
            application.registerForRemoteNotifications()
        }

    }
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {

        let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
        var tokenString = ""

        for i in 0..<deviceToken.length {
            tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
        }

       NSUserDefaults.standardUserDefaults().setObject(tokenString, forKey: "DeviceToken")
        NSUserDefaults.standardUserDefaults().synchronize()
    }

    func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
        print(error.localizedDescription)
    }

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

    let aps = userInfo["aps"] as! [String: AnyObject]

    let data = aps["data"]  as! [String: AnyObject]
    let type = aps["type"] as! Int

      //Do something when app is active
    if UIApplication.sharedApplication().applicationState == UIApplicationState.Active {

        switch type {
        case 0:
            let custName = data["customerName"] as! String
            let notification = CWStatusBarNotification()
            notification.notificationStyle = .NavigationBarNotification
            notification.notificationAnimationInStyle = .Top
            notification.notificationLabelBackgroundColor =  UIColor(red: 0, green: 0, blue: 0, alpha: 0.8)
            notification.notificationLabelTextColor = UIColor.whiteColor()
            notification.notificationLabelFont = UIFont.boldSystemFontOfSize(15)
            notification.displayNotificationWithMessage("\(custName) shorlisted you", forDuration: 3.0)

            notification.notificationTappedClosure = {

                NSNotificationCenter.defaultCenter().postNotificationName("AgentReadyNotification", object: self)

                notification.dismissNotification()
            }

            break

        default:
            break
        }

    } else  {

                   // Do something else when your app is in the background


        switch type {
        case 0 :

             NSNotificationCenter.defaultCenter().postNotificationName("AgentReadyNotification", object: self)



            break

        default:


            break

        }
    }

}

func applicationWillResignActive(application: UIApplication) {

    print(" applicationWillResignActive")
}

func applicationDidEnterBackground(application: UIApplication) {

    print(" applicationDidEnterBackgroundndddddddddddddd")
}

func applicationWillEnterForeground(application: UIApplication) {

     print(" applicationWillEnterForeground")

  }

func applicationDidBecomeActive(application: UIApplication) {

    print(" applicationDidBecomeActive")

}

func applicationWillTerminate(application: UIApplication) {

    print(" applicationWillTerminate")
       }

}

//This code is from app delegate.swift //Now code from the view controller where push is handled

import UIKit


class AgentAllTab: UITableViewController ,UIPopoverPresentationControllerDelegate ,AgentFilterDelegate {


     var allQuoteId = String()


    var filterTitle = "Market"



    var quotes: [[String: AnyObject]] = [[:]]       //VALUE FOR RESPONSE DICT
    var newQuoteDict: Dictionary<String, String> = [String: String]()   // DECLARING DICTIONARY FOR POST PARAMETERS

      override func viewDidLoad() {
        super.viewDidLoad()

        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AgentAllTab.readyNotificationAction), name: "AgentReadyNotification", object: nil)

if ( NSUserDefaults.standardUserDefaults().objectForKey("notificationlauch") != nil){

           NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AgentAllTab.readyNotificationAction), name: "NotificationLaunchReady", object: nil)
            NSNotificationCenter.defaultCenter().postNotificationName("NotificationLaunchReady", object: self)

 NSUserDefaults.standardUserDefaults().removeObjectForKey("notificationlauch")
            NSUserDefaults.standardUserDefaults().synchronize()
            return
        }

executeFetch("/Market_all/")

 }




   override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return quotes.count
    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if filterTitle == "Ready"{
        cell = tableView.dequeueReusableCellWithIdentifier("AgentAllTabReadyCell", forIndexPath: indexPath) as! AgentAllTabCellSubClass

            if(quotes[indexPath.row].count == 0){
           //normal code to hide all content of cell
         }
    }else{
       //code in  case we get data
   }else{
       //Code for other filter title same as above

    }
    return cell
}

func executeFetch(apiurl : String){

  //function to fetch data from server and feed into uitableviewcontroller

}

//Function to handle the push notification func readyNotificationAction(notification:NSNotification) {

    filterTitle = "Ready"
    self.tabBarController?.tabBar.hidden = true
    executeFetch("/agentReady/")

}

}

Upvotes: 0

Views: 825

Answers (1)

Anand Yadav
Anand Yadav

Reputation: 489

Just one line of removal of code made things work perfectly, i was adding the observer in didFinishLaunchingWithOptions method. My corrected code is below,

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch.

let barAppearace = UIBarButtonItem.appearance()
barAppearace.setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -60), forBarMetrics:UIBarMetrics.Default)  //CODE TO REMOVETITLE OFACK BUTTON ITEM IN NAVIGATIION CONTROLLER


let notificationTypes : UIUserNotificationType = [.Alert, .Badge, .Sound]
let notificationSettings : UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)




if let notification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? [String: AnyObject] {

//Removed this observer from here and placed it only where it was required i.e.the desired viewcontroller

     NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AgentAllTab.readyNotificationAction), name: "AgentReadyNotification", object: nil)

// Also add deinit in the place where you place this observer and remove the observer from the viewcontroller so that observer is removed from notification center when app is terminated

let userInfo = launchOptions![UIApplicationLaunchOptionsRemoteNotificationKey] as? [String: AnyObject]

    let aps = userInfo!["aps"] as! [String: AnyObject]
    print("Remote noti data from didFinishLaunchingWithOptions \(aps)")

    let data = aps["data"]  as! [String: AnyObject]
    let type = aps["type"] as! Int
    print("notification TYPE  \(type)")

switch type { case 0 :

        NSUserDefaults.standardUserDefaults().setObject(aps, forKey: "notificationlauch")

    break
   default:
   break

}

return true

}

//The rest of things remained same, Thank you @David V

Upvotes: 0

Related Questions