CloudKit错误处理-重试逻辑 [英] CloudKit error handling - retry logic
问题描述
我想像Apple希望我们所做的那样,在我的应用程序中添加出色的CloudKit错误处理.我想立即保存和修改记录.这是我的基本保存逻辑...
I want to put excellent CloudKit error handling in my app as Apple wants us to do. I want to save and modify a record right now. Here is my basic save logic...
func addNewRecord(managedObj: NSManagedObject) {
let newRec = managedObj.convertToCkRecord()
publicDB.saveRecord(newRec, completionHandler: saveHandler)
}
func saveHandler(savedRecord: CKRecord?, error: NSError?) {
// handle errors here
if let error = error {
if error.code == CKErrorCode.NotAuthenticated.rawValue {
// debug
print("Not authentricated")
}
else if error.code == CKErrorCode.NetworkFailure.rawValue {
print("Network failure!!")
if let retryAfterValue = error.userInfo[CKErrorRetryAfterKey] as? NSTimeInterval {
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(retryAfterValue * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
// THIS IS WHERE I GET STUCK, WHERE DO I FIND THE FAILED CKRECORD FOR RETRY?
// IS IT IN USERINFO SOMEWHERE?
//self.saveHandler(savedRecord, error: error)
}
}
}
}
else {
print("Save was a success! \(savedRecord)")
}
}
这似乎应该是基本的,但是我看到的每个示例都带有注释//retry
或//handle error
,包括在WWDC教程中应该进行错误处理的地方.我想知道的是如何找到对失败的CKRecord的引用?由于多线程问题,将其存储在本地变量中似乎无法正常工作.我尝试将其添加到队列中,但是其他线程也可以进入该队列,因此我担心竞争状况.
This seems it should be basic, but every example I see about this just has a comment //retry
or //handle error
, including in the WWDC tutorials where the error handling should go. What I want to know is how do I find a reference to my failed CKRecord? Storing it in a local variable seems like it won't work because of the multithreading issue. I tried adding it to a queue, but other threads could get to that queue as well so I worry about race conditions.
推荐答案
使用dispatch_after
代替使用NSTimer
.
print("Network failure!!")
if let retryAfterValue = error.userInfo[CKErrorRetryAfterKey] as? NSTimeInterval {
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(retryAfterValue * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
saveHandler(saveRecord: saveRecord, error: error)
}
}
这是我用于所有记录修改和删除的辅助方法(在Objective-C中).它处理常见的错误和重试.
Here is a helper method (in Objective-C) that I use for all record modification and deletion. It deals with common errors and retries.
- (void)modifyRecords:(NSArray<CKRecord *> *)records andDeleteRecords:(NSArray<CKRecordID *> *)deleteIds completion:(void (^)(NSArray<CKRecord *> *savedRecords, NSArray<CKRecordID *> *deletedRecordIDs, NSError *error))completion {
CKModifyRecordsOperation *op = [[CKModifyRecordsOperation alloc] initWithRecordsToSave:records recordIDsToDelete:deleteIds];
op.savePolicy = CKRecordSaveAllKeys;
op.modifyRecordsCompletionBlock = ^(NSArray *savedRecords, NSArray *deletedRecordIDs, NSError *operationError) {
NSError *returnError = operationError;
if (operationError) {
switch (operationError.code) {
case CKErrorRequestRateLimited:
case CKErrorServiceUnavailable:
case CKErrorZoneBusy:
{
double delay = 3.0;
NSNumber *delayVal = operationError.userInfo[CKErrorRetryAfterKey];
if (delayVal) {
delay = delayVal.doubleValue;
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
[self modifyRecords:records andDeleteRecords:deleteIds completion:completion];
});
}
return;
case CKErrorPartialFailure:
{
if (savedRecords.count || deletedRecordIDs.count) {
returnError = nil;
}
break;
}
default:
{
NSLog(@"Unhandled error in modify/deleteRecords: %@", operationError);
}
break;
}
}
if (completion) {
completion(savedRecords, deletedRecordIDs, returnError);
}
};
[someCloudKitDatabase addOperation:op];
}
如果只想添加/修改记录,请将nil
传递给deleteIds
参数.
If you only want to add/modify a record, pass nil
to the deleteIds
parameter.
这与Swift 3中的帮助程序方法相同(尚未经过测试,但除最后一行外,它仍可以编译).
Here's the same helper method in Swift 3 (this has not been tested but it does compile except for the last line).
func modifyRecords(_ records: [CKRecord]?, andDelete deleteIds: [CKRecordID]?, completionHandler: @escaping ([CKRecord]?, [CKRecordID]?, Error?) -> Void) {
let op = CKModifyRecordsOperation(recordsToSave: records, recordIDsToDelete: deleteIds)
op.savePolicy = .allKeys
op.modifyRecordsCompletionBlock = { (_ savedRecords: [CKRecord]?, _ deletedRecordIds: [CKRecordID]?, _ operationError: Error?) -> Void in
var returnError = operationError
if let ckerror = operationError as? CKError {
switch ckerror {
case CKError.requestRateLimited, CKError.serviceUnavailable, CKError.zoneBusy:
let retry = ckerror.retryAfterSeconds ?? 3.0
DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + retry, execute: {
modifyRecords(records, andDelete: deleteIds, completionHandler: completionHandler)
})
return
case CKError.partialFailure:
if (savedRecords != nil && savedRecords!.count > 0) || (deletedRecordIds != nil && deletedRecordIds!.count > 0) {
returnError = nil
}
default:
break
}
}
completionHandler(savedRecords, deletedRecordIds, returnError)
}
someCloudKitDatabase.add(op)
}
这篇关于CloudKit错误处理-重试逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!