2017-06-14 104 views
2

我找不到合適的正確方法來檢查CKRecord訂閱是否已經存在,如果訂閱不存在,則訂閱它以獲取推送通知。檢查記錄訂閱是否已在CloudKit中存在

我已經實現了訂閱本身,它的響應,但每次我進入正確的視圖控制器時,我總是試圖再次訂閱和服務器回覆一個錯誤,如果該訂閱已經存在 - 我的問題是:是有沒有辦法檢查訂閱是否存在,而不是嘗試創建它並等待服務器響應?

這裏是我如何訂閱記錄:

// Create the predicate 
let predicate = NSPredicate(format: "recordId = %@", RECORD_ID) 

// Create a subscription specifying the record type, predicate and notification options 
let subscription = CKQuerySubscription(recordType: "Tabs", predicate: predicate, options: [.firesOnRecordUpdate, .firesOnRecordCreation]) 

// Create a CloudKit notification object 
let notificationInfo = CKNotificationInfo() 
notificationInfo.alertLocalizationKey = "Updates have been made" 
notificationInfo.shouldBadge = true 

// Set the subscriptor's notification object to the new CloudKit notification object 
subscription.notificationInfo = notificationInfo 

// Save the subscription to the database 
let publicDatabase = CKContainer.default().publicCloudDatabase 
publicDatabase.save(subscription) { (subs, err) in 
    if let err = err { 
     print("Failed to save subscription:", err) 
     return 
    } 
} 

感謝

回答

1

您可以使用fetchAllSubscriptionsWithCompletionHandler查詢所有現有的潛艇,那麼你就可以在完成處理返回的每個子查詢subscriptionID財產。客觀c版本如下:

[publicDatabase fetchAllSubscriptionsWithCompletionHandler:^(NSArray<CKSubscription *> * _Nullable subscriptions, NSError * _Nullable error) 
    { 
     NSMutableArray *subIDs = [NSMutableArray new]; 
     for (CKSubscription *sub in subscriptions) 
     { 
      if ([sub.subscriptionID isEqualToString:@"whatever"]; 
      { 
        //do some stuff 
      } 
     } 
    }]; 

但是,您提到重新進入視圖控制器並重新運行此檢查。並不是說這個檢查每次都會向服務器發出一個請求,因此會計入您的事務和傳輸配額。我建議您在應用程序啓動時運行此檢查一次,然後將每個子的狀態保存在類變量中,這樣您就不必通過不必要的調用重複查詢服務器。