0
I am currently learning local notification, but i have a few problems in my test project.


import UIKit
    import UserNotifications
    import Alamofire
    import SwiftyJSON
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
        var window: UIWindow?
        let playersStore = PlayersStore()

          var backgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid

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

            let navController = window!.rootViewController as! UINavigationController
            let itemsController = navController.topViewController as! ListPlayersVC


            let center = UNUserNotificationCenter.current()

            center.requestAuthorization(options: [.alert, .sound]) {(accepted, error) in
                if !accepted {

                }
            }



            let category = UNNotificationCategory(identifier: "myCategory", actions: [], intentIdentifiers: [], options: [])
           center.setNotificationCategories([category])
            center.delegate = scheduleNotification() as? UNUserNotificationCenterDelegate



            return true

        }


        func scheduleNotification() {


            let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)

            let content = UNMutableNotificationContent()



                    for i in playersStore.allItems {
                        let todoEndpoint: String = "url1"


                        let allowedCharacterSet = (CharacterSet(charactersIn: " ").inverted)
                        let escapedString = todoEndpoint.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet)


                        Alamofire.request(escapedString!)
                            .responseJSON {response in

                                guard response.result.error == nil else {
                                    // print(response.result.error!)
                                    print("Error")
                                    return
                                }

                                let todoEndpoint2: String = "url"


                                let allowedCharacterSet = (CharacterSet(charactersIn: " ").inverted)


                                Alamofire.request(escapedString2!)
                                    .responseJSON {response2 in

                                        guard response.result.error == nil else {
                                            //print(response.result.error!)
                                            print("Error2")
                                            return
                                        }




                                        //                guard let json = response.result.value as? [String: Any] else {
                                        //                    print(response.result.error!)
                                        //                    return
                                        //                }
                                        let json2 = JSON(response.result.value!)
                                        let json3 = JSON(response2.result.value!)





                           let test1 = json3["test"]

                                        if test1 != i.test {




                                            i.test = test1

                                    self.savechanges()
                                            content.title =  "test"
                                            content.subtitle = "testtest"
                                            content.body = "testtest"
                                            content.badge = 1
                                            content.categoryIdentifier = "myCategory"



                                            let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request) {(error) in
                                                if let error = error {
                                                    print("\(error)")
                                                }
                                            }


                                        }
                                        return




        }
                        }

            }

        }
        func applicationWillResignActive(_ application: UIApplication) {
            // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
            // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
        }
        func applicationDidEnterBackground(_ application: UIApplication) {
            // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
            // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
            let savePlayersStore = playersStore.saveChanges()
            if (savePlayersStore) {
                print("saves all items")
            } else {
                print("error, could not save any of the item")
            }




        }
        func applicationWillEnterForeground(_ application: UIApplication) {


        }
        func applicationDidBecomeActive(_ application: UIApplication) {
            // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        }
        func applicationWillTerminate(_ application: UIApplication) {
            // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        }

        func savechanges() {
            let savePlayersStore = playersStore.saveChanges()
            if (savePlayersStore) {
                print("saves all items")
            } else {
                print("error, could not save any of the item")
            }

        }

        }

sorry for bad editing / explaining..

i hope you will understand me now

so this is my source code

what i want to do with local notification:

contact the server (testwise it is set to 60seconds) (working)

if there is an update, show a notification(working)

save the new value in background (self.savechanges()) (does not work) so a new notification will not generate if repeat is on true (does not work)

i tested my app with trigger repeat false, but my app will only show one notification and ignores any future changes furthermore it ignores all items in my playerstore, so that only one notification will be published

i hope you understand what i am trying to accomplish

thank you very much!

Wizzard
  • 1
  • 2
  • 2
    Your question is quite unclear. – nayem Jun 28 '17 at 08:11
  • A general tip for asking good questions: paste all your code into Xcode, then click `ctrl + I` to fix the indentation. Then edit your question with better indentation of your code. Also delete the blank lines... Still unclear what you'r asking – mfaani Jun 28 '17 at 10:56
  • thank you very much, i edited my post! – Wizzard Jun 28 '17 at 15:07

1 Answers1

0

If your app is in the background and you have to call some background activity, then you have to make your app enable to Background mode.

Go to Target -> Capabilities -> On background mode.

Rajeev Singh
  • 198
  • 1
  • 11
  • i tried this like explained here (https://developer.apple.com/documentation/uikit/uiapplication/1623031-beginbackgroundtask) but i couldnt get that to work. any further ideas? thanks! – Wizzard Jun 28 '17 at 15:58