多个ios推送通知会导致应用程序崩溃。由于信号6(SIGABRT)而终止

时间:2016-05-20 07:13:02

标签: notifications apple-push-notifications ios9 swift2.2

enter image description here这些是应用崩溃之前和之后的图像,控制台只显示消息来自调试器的消息:由于信号6终止 enter image description here [[ ![我的应用程序通过推送通知成功启动(未运行时),并且我获得了所需的屏幕和结果,但在应用程序处于活动状态时再次通过通知时会再次收到通知时崩溃。当应用程序正常启动从主屏幕通知功能和行动工作正常应用程序活动和后台。我发布我的代码下面请帮助我。

当我从收到的通知中启动我的应用程序时,应用程序成功午餐并转到受尊重的窗口,现在再次当应用程序打开时我收到通知然后应用程序崩溃,意味着每当我的应用程序未在后台或前台运行时我使用通知启动我的应用..然后当我收到通知应用程序崩溃时再次

我的代码如下,请帮助

导入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)")

切换类型{             案例0:

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

        break
       default:
       break


}

返回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")
       }

}

//此代码来自app delegate.swift //现在来自视图控制器的代码处理推送

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

}

//处理推送通知的函数 func readyNotificationAction(通知:NSNotification){

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

}

}

1 个答案:

答案 0 :(得分:0)

只需删除一行代码就可以完美地运行,我在didFinishLaunchingWithOptions方法中添加了观察者。 我更正后的代码如下,

func application(application:UIApplication,didFinishLaunchingWithOptions launchOptions:[NSObject:AnyObject]?) - &gt;布尔{     //在应用程序启动后覆盖自定义点。

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)

//还在放置此观察者的位置添加deinit,并从viewcontroller中删除观察者,以便在终止app时将观察者从通知中心移除

让userInfo = launchOptions![UIApplicationLaunchOptionsRemoteNotificationKey]为? [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)")

切换类型{案例0:

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

    break
   default:
   break

}

返回true

}

//剩下的事情保持不变,谢谢@David V