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")
}
}
}
извините за плохое редактирование/объяснение..
Я надеюсь, ты поймешь меня сейчас
так что это мой исходный код
что я хочу сделать с локальным уведомлением:
связаться с сервером (по тесту установлено 60 секунд) (работает)
если есть обновление, показать уведомление (работает)
сохранить новое значение в фоновом режиме (self.savechanges()) (не работает), поэтому новое уведомление не будет генерироваться, если для повтора установлено значение true (не работает)
я протестировал свое приложение с повторением триггера false, но мое приложение будет отображать только одно уведомление и игнорировать любые будущие изменения, кроме того, оно игнорирует все элементы в моем плеере, поэтому будет опубликовано только одно уведомление
Надеюсь, вы понимаете, чего я пытаюсь добиться
большое спасибо!
ctrl + I
, чтобы исправить отступ. Затем отредактируйте свой вопрос с лучшим отступом вашего кода. Также удалите пустые строки... Все еще неясно, о чем вы спрашиваете. - person Honey   schedule 28.06.2017