iOS網絡編程-解決iCloud文檔存儲過程中文檔衝突問題
iCloud文檔在保存的過程中難免會發生衝突,我們必須要有一套解決衝突的策略。策略的采用要根據用戶的需求而定,有的簡單有的複雜,最簡單的是直接使用當前版本覆蓋衝突版本。複雜的策略,例如:如果是兩個文本文件衝突,可以將兩個衝突點列出來,讓用戶來判斷再進行保存。
我們采用的策略是使用當前版本覆蓋以前的版本。解決衝突首先需要在updateUbiquitousDocuments:方法中注冊UIDocumentStateChangedNotification通知:
//當iCloud中的文件變化時候調用 - (void)updateUbiquitousDocuments:(NSNotification *)notification { … … if (_myCloudDocument) { //注冊CloudDocument對象到文檔協調者,文檔狀態變化才能收到通知 [NSFileCoordinator addFilePresenter:_myCloudDocument]; ① //注冊文檔狀態變化通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resolveConflict:) name:UIDocumentStateChangedNotification object:nil]; ② } } //文檔衝突解決 - (void)resolveConflict:(NSNotification *)notification { if (_myCloudDocument && _myCloudDocument.documentState == UIDocumentStateInConflict) { ③ NSLog(@”衝突發生”); //文檔衝突解決策略 NSError *error; if (![NSFileVersion removeOtherVersionsOfItemAtURL: _ myCloudDocument.fileURL error:&error]) { ④ NSLog(@”移除其它的文檔: %@”, [error localizedFailureReason]); return; } _myCloudDocument.contents = _txtContent.text; ⑤ [_myCloudDocument updateChangeCount:UIDocumentChangeDone]; ⑥ } [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDocumentStateChangedNotification object:nil]; ⑦ //從文檔協調者中解除CloudDocument對象 [NSFileCoordinator removeFilePresenter:_myCloudDocument]; ⑧ }
出自《iOS網絡編程與雲端應用最佳實踐》作者:關東升 @tony_關東升
最後更新:2017-04-03 18:51:47