Я хочу использовать подписку Cloudkit для получения уведомления, когда в базу данных будет вставлена новая запись.
import Foundation
import UIKit
import CoreData
import CloudKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound ,.badge]) { authorized, error in
guard error == nil, authorized else {
// not authorized...
return
}
// subscription can be created now \o/
}
UIApplication.shared.registerForRemoteNotifications()
return true
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
print("Recieved - Remote Notification")
}
}
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
let contentView = ContentView()
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
..... standart UIWindowSceneDelegate methods ....
}
import SwiftUI
import CloudKit
struct ContentView: View {
var body: some View {
VStack {
Button(action: {
self.sendMessage()
}) {
Text("send Message")
}.padding()
Button(action: {
self.loadData()
}) {
Text("load records")
}.padding()
}.onAppear(perform: {
let publicData = CKContainer.default().publicCloudDatabase
let subs = CKQuerySubscription(recordType: "CD_Message",
predicate: NSPredicate(value: true),
options: [.firesOnRecordCreation])
let notification = CKSubscription.NotificationInfo()
notification.alertBody = "New Message"
notification.soundName = ""
notification.shouldBadge = true
subs.notificationInfo = notification
publicData.save(subs) { savedSubscription, error in
guard let savedSubscription = savedSubscription, error == nil else {
print(error)
return
}
print("Subscription")
}
})
}
//Methods to test notifications via creation
func sendMessage() {
let message = CKRecord(recordType: "CD_Message")
let publicData = CKContainer.default().publicCloudDatabase
publicData.save(message) { (record:CKRecord?, error:Error?) in
if error != nil {
print(error)
} else {
print("Data Has been send")
self.loadData()
}
}
}
func loadData(){
var messages: [CKRecord] = []
let publicData = CKContainer.default().publicCloudDatabase
let query = CKQuery(recordType: "CD_Message", predicate: NSPredicate(value: true))
//query.sortDescriptors = [NSSortDescriptor(key:"creationDate", ascending: false)]
//query.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: false)]
publicData.perform(query, inZoneWith: nil){ (results:[CKRecord]?, error:Error?) in
if let mess = results {
messages = mess
print(messages.count)
}
if let error = error {
print(error)
}
}
}
}
Следующий минимальный пример отлично работает на моем iPhone. Когда я создаю новую запись через панель инструментов или с IPad, я получаю уведомление, и didReceiveRemoteNotification
вызывается.
Тем не менее, я не получаю уведомление на IPad, когда я создаю новую запись на iPhone. Так что он работает только на iPhone, но не на Ma c или iPad. Я проверил все настройки уведомлений на своем iPad и пробовал это несколько раз, но didReceiveRemoteNotification
не вызывается, и я не получаю уведомление pu sh. Это также не работает на Ма c, didReceiveRemoteNotification
не вызывается. Я также попробовал второй IPad, и я получил тот же результат
Чего мне не хватает?
РЕДАКТИРОВАТЬ: Я только что узнал, что
didRegisterForRemoteNotificationsWithDeviceToken
вызывается из моего iPhone, но не для моего iPad. К сожалению, я не получаю сообщение об ошибке:
didFailToRegisterForRemoteNotificationsWithError