如何通过CKFetchNotificationChangesOperation避免不经常的网络数据使用?

时间:2014-10-09 11:00:26

标签: ios cloudkit

WWDC 2014高级Cloudkit视频建议:每次收到推送时,都应该检查通知集合,找到可能遗漏的任何内容。

我也这样做,但是如果在很短的时间内在同一条记录上发生了2次更新,我会得到2次推送通知,每次都会使用网络两次,所以notificationChangedBlock会被称为2x2 = 4次,但相关的只有2(如果没有错过任何通知则为0)。

这不是很有效,你的做法有何不同?

func application(application: UIApplication!, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]!) {
    Utility.checkNotifications()
}

class func checkNotifications() {

    let defaultContainer = CKContainer.defaultContainer()
    let publicDatabase = defaultContainer.publicCloudDatabase

    let fnco = CKFetchNotificationChangesOperation(previousServerChangeToken: previousChangeToken)
    fnco.notificationChangedBlock = {notification in

        readNotificationIDs.append(notification.notificationID)
        if previousChangeToken != nil {
            Utility.processNotification(notification)
        }
    }
    fnco.fetchNotificationChangesCompletionBlock = {serverChangeToken, error in

        previousChangeToken = serverChangeToken
        let op = CKMarkNotificationsReadOperation(notificationIDsToMarkRead: readNotificationIDs)
        op.start()
    }
    defaultContainer.addOperation(fnco)
}

1 个答案:

答案 0 :(得分:1)

我使用这个老技巧:

[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(fetchPendingNotifications) object:nil];
[self performSelector:@selector(fetchPendingNotifications) withObject:nil afterDelay:2.0f];