Несколько push-уведомлений ios вызывают сбой приложения. Завершено из-за сигнала 6(SIGABRT)
Это образы до и после сбоя приложения, консоль показывает только сообщение Сообщение от отладчика: прекращено из-за сигнала 6
[[
Мое приложение запускается (когда оно не запущено) успешно из push-уведомления, а также я получаю нужный экран и результат, но падает, когда оно снова получает уведомление от касания уведомления, когда приложение активно. Когда приложение запускается в обычном режиме с помощью функции уведомлений на главном экране, и действие отлично работает, когда приложение активно и в фоновом режиме. Я публикую нижеприведенный код, пожалуйста, помогите мне.
Когда я запускаю свое приложение из полученного уведомления, приложение запускается успешно и переходит в уважаемое окно, теперь снова, когда я получаю уведомление, когда приложение открыто, затем приложение вылетает, то есть, когда мое приложение не работает в фоновом режиме или на переднем плане, и я запускаю свое приложение используя уведомление.. и затем снова, когда я получаю уведомление приложение падает
Мой код ниже, пожалуйста, помогите
импорт 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)")
тип переключателя { case 0:
NSUserDefaults.standardUserDefaults().setObject(aps, forKey: "notificationlauch")
break
default:
break
}
вернуть истину
}
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 (приложение: 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")
}
}
// Этот код взят из приложения Delegate.swift // Теперь код из контроллера представления, где обрабатывается push
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
}
// Функция для обработки функции push-уведомлений readyNotificationAction(tification: NSNotification) {
filterTitle = "Ready"
self.tabBarController?.tabBar.hidden = true
executeFetch("/agentReady/")
}
}
1 ответ
Всего одна строка удаления кода заставляла вещи работать идеально, я добавлял наблюдателя в метод didFinishLaunchingWithOptions. Мой исправленный код ниже,
Приложение func (приложение: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Точка переопределения для настройки после запуска приложения.
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] {
// Удалил этого наблюдателя отсюда и поместил его только там, где он был нужен, т.е. в желаемый viewcontroller
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AgentAllTab.readyNotificationAction), name: "AgentReadyNotification", object: nil)
// Также добавляем deinit в место, где вы размещаете этого наблюдателя, и удаляете наблюдателя из viewcontroller, чтобы наблюдатель был удален из центра уведомлений, когда приложение завершается
пусть userInfo = launchOptions![UIApplicationLaunchOptionsRemoteNotificationKey] как? [Строка: 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)")
тип переключателя {case 0:
NSUserDefaults.standardUserDefaults().setObject(aps, forKey: "notificationlauch")
break
default:
break
}
вернуть истину
}
// Остальные вещи остались прежними, спасибо @David V