2017-01-16 5 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) 
    } 
} 
関連する問題