tvOS中的CloudKit订阅

时间:2016-04-22 03:07:47

标签: swift cloudkit tvos

我正在尝试使用CloudKit和CKSubcription在几台Apple TV之间同步数据。当我添加,删除或更新记录时,问题是application:didReceiveRemoteNotification:永远不会被调用。我相信我正在正确配置订阅,并且我已确认它们已添加到CloudKit仪表板中。我一再尝试在仪表板中重置开发环境,但这没有帮助。我真的不想创建一个定时器来经常获取。谢谢你的帮助!

另外,我在CloudKit中使用私有数据库,而不是公共数据库,如果重要的话。

这是我的代码:

AppDelegate.swift

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    CloudKitManager.subscribeToItemUpdates()
    application.registerForRemoteNotifications()

    ...

    return true
}

CloudKitManager.swift

class func subscribeToItemUpdates() {

    if let uuid = UIDevice.currentDevice().identifierForVendor?.UUIDString {

        saveSubscriptionWithIdentifier(uuid + "create", options: CKSubscriptionOptions.FiresOnRecordCreation)
        saveSubscriptionWithIdentifier(uuid + "update", options: CKSubscriptionOptions.FiresOnRecordUpdate)
        saveSubscriptionWithIdentifier(uuid + "delete", options: CKSubscriptionOptions.FiresOnRecordDeletion)
    }

}

class func saveSubscriptionWithIdentifier(identifier: String, options: CKSubscriptionOptions) {

    let sub = CKSubscription(recordType: "Message", predicate: NSPredicate(value: true), subscriptionID: identifier, options: options)
    sub.notificationInfo = CKNotificationInfo()

    let publicDatabase = CKContainer.defaultContainer().publicCloudDatabase
        publicDatabase.saveSubscription(sub) { (savedSubscription, error) -> Void in
        if error != nil {
            print("Error saving CloudKit subscription \(error)")
        }
        else {
            print("Saved subscription to CloudKit", savedSubscription)
        }
    }
}

1 个答案:

答案 0 :(得分:0)

tvOS与iOS之间存在细微差别。在我的演示应用程序中,我这样处理:

#if os(tvOS)
//This will only be called when your app is active. So this is what you should use on tvOS
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    EVLog("Push received")
    EVCloudData.publicDB.didReceiveRemoteNotification(userInfo, executeIfNonQuery: {
        EVLog("Not a CloudKit Query notification.")
    }, completed: {
        EVLog("All notifications are processed")
    })
}
#else
// Process al notifications even if we are in the background. tvOS will not have this event
// Make sure you enable background notifications in the app settings. (entitlements: pushnotifications and  backgrounds modes - notifications plus background fetch)
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
    EVLog("Push received")
    EVCloudData.publicDB.didReceiveRemoteNotification(userInfo, executeIfNonQuery: {
        EVLog("Not a CloudKit Query notification.")
    }, completed: {
        EVLog("All notifications are processed")
        completionHandler(.NewData)
    })
}
#endif

有关详细信息,请参阅EVCloudKitDao