2017-01-16 62 views

回答

0

簡單地做這樣的:

func fetchPendingNotifications() { 

    var queryNotifications = [CKQueryNotification]() 

    let operation = CKFetchNotificationChangesOperation(previousServerChangeToken: nil) 
    let operationQueue = OperationQueue() 

    operation.notificationChangedBlock = { notification in 

     if let queryNotification = notification as? CKQueryNotification { 
      queryNotifications.append(queryNotification) 
     } 
    } 

    operation.fetchNotificationChangesCompletionBlock = { _, error in 

     if error == nil { 

      self.perform(queryNotifications: queryNotifications) { _ in 

       //do sth on success 
      } 
     } 
    } 

    operationQueue.addOperation(operation) 
} 

輔助功能:

private func perform(queryNotifications: [CKQueryNotification], completion: ErrorHandler? = nil) { 

    var currentQueryNotifications = queryNotifications 

    if let queryNotification = currentQueryNotifications.first { 

     currentQueryNotifications.removeFirst() 

     if queryNotification.queryNotificationReason == .recordCreated || queryNotification.queryNotificationReason == .recordUpdated { 

      //fetch the record from cloud and save to core data 
      self.fetchAndSave(with: queryNotification.recordID!) { error in 

       if error == nil { 

        OperationQueue().addOperation(CKMarkNotificationsReadOperation(notificationIDsToMarkRead: [queryNotification.notificationID!])) 
        self.perform(queryNotifications: currentQueryNotifications, completion: completion) 

       } else { 
        completion?(error) 
       } 
      } 

     } else { 
      //delete record from coredata 
      self.delete(with: queryNotification.recordID!) { error in 

       if error == nil { 

        OperationQueue().addOperation(CKMarkNotificationsReadOperation(notificationIDsToMarkRead: [queryNotification.notificationID!])) 
        self.perform(queryNotifications: currentQueryNotifications, completion: completion) 

       } else { 
        completion?(error) 
       } 
      } 
     } 

    } else { 

     completion?(nil) 
    } 
}