iCloud -- Subscribing to Record Changes


It’s inefficient for your app to repeat a query when the results are mostly the same as the last query. Instead,subscribe to record changes, and let the server run the query in the background. The server will notify your app of changes that interest the user or app. For example, if one user of your app is interested in artwork bya certain artist, your app can be notified when new artwork by that artist is uploaded.

在爲您的應用程序重複查詢時,結果大多數是和最後一次查詢結果是一樣的,這樣的查詢非常低效率。相反,訂閱記錄的變化,並讓服務器在後臺運行查詢。服務器將用戶或應用程序感興趣的改變通知給你的app。例如,如果你的應用程序中的一個用戶對BYA某個藝術家感興趣,則當有新的作品由該藝術家上傳時你的應用程序可以被通知



1.Save Subscriptions to the Database 保存訂閱到數據庫
In your code, create a subscription object specifying the record type, predicate, and types of changes you want to be notified about. Then save the subscription object to the database.在你的代碼中,創建一個由你想被通知的改變所構成的認購對象,然後保存該訂閱對象到數據庫中
1.1To create and save a subscription
1. Create a predicate object.

NSPredicate *predicate = [NSPredicatepredicateWithFormat:@"artist = %@",@"Mei Chen"];

2. Create a subscription specifying the record type, predicate, and notification options.

CKSubscription *subscription = [[CKSubscriptionalloc]initWithRecordType:@"Artwork"predicate:predicate options:CKSubscriptionOptionsFiresOnRecordCreation];

The possible values for theoptionsparameter are: CKSubscriptionOptionsFiresOnRecordCreation,CKSubscriptionOptionsFiresOnRecordDeletion,CKSubscriptionOptionsFiresOnRecordUpdate, and CKSubscriptionOptionsFiresOnce. Becausetheoptionsparameter is a bitmask, you can subscribe to any combination of the type of changes. Forexample, you can passCKSubscriptionOptionsFiresOnRecordCreation |CKSubscriptionOptionsFiresOnRecordUpdateas the options:parameter to receive notificationof all new data. 

3. Create a CloudKit notification object.

CKNotificationInfo *notificationInfo = [CKNotificationInfonew];

    notificationInfo.alertActionLocalizationKey =@"New artwork by your favorite artist";

    notificationInfo.shouldBadge = YES;

To display a localized string to the user, set the notification’s alertLocalizationKey property (not the alertBody property).


4. Set the subscription’s notification object to the new CloudKit notification object.

subscription.notificationInfo = notificationInfo;

5. Save the subscription to the database.

  CKDatabase *publicDatabase = [[CKContainerdefaultContainer]publicCloudDatabase];

    [publicDatabase saveSubscription:subscriptioncompletionHandler:^(CKSubscription *subscription,NSError *error) {

        if (error) {

            

        }

    }];

2.Verify Your Steps
Verify that the subscription was saved to the schema. In CloudKit Dashboard, the subscription object appears as a subscription type in the schema.
1. In CloudKit Dashboard, choose the container used by your app from the pop-up menu in the upper-left corner.
2. Under Schema, click Subscription Types.

     The subscriptions appear in the second column.
3. If necessary, select a subscription.
   The subscription properties appear in the detail area.

2.Register for Push Notifications 註冊推送通知
Saving subscriptions to the database doesn’t automatically configure your app to receive subscription notifications. CloudKit uses the Apple Push Notification service (APNs) (page $@) to send subscription notifications to your app, so your app needs to register for push notifications to receive them.
For iOS apps, add this code to the application:didFinishLaunchingWithOptions: protocol method to register for push notifications:

將訂閱保存到數據庫不會自動配置您的應用程序來接收訂閱通知。 CloudKit使用蘋果推送通知服務(APNS)發送訂閱通知到您的應用程序,所以您的應用程序需要註冊推送通知來接收它們。
對於iOS應用程序,該代碼添加到 application:didFinishLaunchingWithOptions:方法來註冊推送通知:

// Register for push notifications

    UIUserNotificationSettings *notificationSetting = [UIUserNotificationSettingssettingsForTypes:UIUserNotificationTypeAlertcategories:nil];

    [application registerUserNotificationSettings:notificationSetting];

    [application registerForRemoteNotifications];


For Mac apps, implement the applicationDidFinishLaunching: protocol method to register for push notifications.
For both iOS and Mac apps, optionally implement the application:didRegisterForRemoteNotificationsWithDeviceToken: and application:didFailToRegisterForRemoteNotificationsWithError: methods to take the appropriate action when the app successfully or unsuccessfully registers for push notifications.

Note: You don’t need to enable push notifications for the app’s explicit App ID in Member Center to receive subscription notifications. Xcode automatically adds the APNs entitlement to your entitlement file when you enable CloudKit.


3.Handle Push Notifications in Code  用代碼處理推送通知
Next, implement the application:didReceiveRemoteNotification: method to process subscription notifications when they arrive. For iOS apps, implement the UIApplicationDelegate protocol method and for Mac apps, implement the NSApplicationDelegate protocol method. For example, implement this method to update views when records matching your predicate are created, updated, or deleted.

接下來,實現 application:didReceiveRemoteNotification:方法來處理訂閱通知,當他們到達。對於iOS應用程序,實現UIApplicationDelegate協議方法,對於Mac應用程序,實現NSApplicationDelegate協議方法。例如,實現此方法時創建的記錄相匹配的謂詞,更新或刪除更新的意見。

1. Add the application:didReceiveRemoteNotification: protocol method to the app’s delegate.

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{

    

}


2. In the application:didReceiveRemoteNotification: method, convert the userInfo parameter to a CKNotification object.

CKNotification *cloudKitNotification = [CKNotificationnotificationFromRemoteNotificationDictionary:userInfo];

3. Get the body of the notification.

NSString *alertBody = cloudKitNotification.alertBody;


4. Get the new or modified record from the CKQueryNotification object.

if (cloudKitNotification.notificationType ==CKNotificationTypeQuery) {

        CKRecordID *recordID = [(CKQueryNotification *)cloudKitNotificationrecordID];

    }

5. Update views or notify the user according to the record changes.


3.Test Subscriptions

You can initially test subscriptions by running your app through Xcode and using CloudKit Dashboard to create, modify, or delete records, as described in Create and Delete Records (page 27). Then fully test subscriptions by running your app on multiple devices. Use one device to make changes and another device to receive the subscription notifications. You use multiple devices because a notification isn’t sent to the same device that originated the notification.
For iOS, use an iOS device (not iOS Simulator) to test subscription notifications. Your app successfully registers for push notifications if a dialog that asks the user’s permission for your app to receive notifications.
您可以通過Xcode中運行你的應用程序,並使用CloudKit儀表板來創建,修改或刪除記錄最初測試訂閱,所描述的創建和刪除記錄。然後通過在多個設備上運行你的應用程序全面測試訂閱。用一臺設備進行修改和另一設備接收訂閱通知。使用多臺設備,因爲不發送通知,以產生該通知相同的設備。
適用於iOS,使用iOS設備(而不是iPhone模擬器)來測試訂閱通知。如果有要求用戶的權限來允許您的應用程序接收通知,那麼你的應用程序成功地註冊了推送通知。

4.Recap
In this chapter you learned how to:
Subscribe to record changes by using a predicate 

Handle subscription notifications








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章