• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 保存 CKRecord 时的错误处理

[复制链接]
菜鸟教程小白 发表于 2022-12-12 08:53:41 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我正在寻找保存 CKRecord 时正确处理错误的示例。根据 Apple docs我应该“使用错误对象中的信息来确定问题是否有解决方法。”

我知道错误对象有一个 userInfo 字典,但我如何确定字典的键是什么以及如何处理错误?

以下示例说明了我当前如何保存 CKRecord:

    CKRecord *record = [[CKRecord alloc] initWithRecordType"MyRecordType"];
[record setValue:[NSNumber numberWithInt:99] forKey"myInt"];

[db saveRecord:record completionHandler:^(CKRecord *savedPlace, NSError *error) {
    // handle errors here
    if (savedPlace) {
        NSLog(@"save successful");
    }else{
        NSLog(@"save unsuccessful");
    }
    if (error) {
        NSLog(@"Error saving %@", error.localizedDescription);
    }

}];

如何改进此代码以解决潜在的保存问题?



Best Answer-推荐答案


在我的图书馆EVCloudKitDao我有一个单独的方法,它将根据错误代码返回错误类型。根据该类型,您可以决定要做什么。这是那个方法:

public enum HandleCloudKitErrorAs {
    case Success,
    Retry(afterSecondsouble),
    RecoverableError,
    Fail
}

public static func handleCloudKitErrorAs(error:NSError?, retryAttemptouble = 1) -> HandleCloudKitErrorAs {
    if error == nil {
        return .Success
    }
    let errorCode:CKErrorCode = CKErrorCode(rawValue: error!.code)!
    switch errorCode {
    case .NetworkUnavailable, .NetworkFailure, .ServiceUnavailable, .RequestRateLimited, .ZoneBusy, .ResultsTruncated:
        // Use an exponential retry delay which maxes out at half an hour.
        var seconds = Double(pow(2, Double(retryAttempt)))
        if seconds > 1800 {
            seconds = 1800
        }
        // Or if there is a retry delay specified in the error, then use that.
        if let userInfo = error?.userInfo {
            if let retry = userInfo[CKErrorRetryAfterKey] as? NSNumber {
                seconds = Double(retry)
            }
        }
        NSLog("Debug: Should retry in \(seconds) seconds. \(error)")
        return .Retry(afterSeconds: seconds)
    case .UnknownItem, .InvalidArguments, .IncompatibleVersion, .BadContainer, .MissingEntitlement, .PermissionFailure, .BadDatabase, .AssetFileNotFound, .OperationCancelled, .NotAuthenticated, .AssetFileModified, .BatchRequestFailed, .ZoneNotFound, .UserDeletedZone, .InternalError, .ServerRejectedRequest, .ConstraintViolation:
        NSLog("Error: \(error)")
        return .Fail;
    case .QuotaExceeded, .LimitExceeded:
        NSLog("Warning: \(error)")
        return .Fail;
    case .ChangeTokenExpired,  .ServerRecordChanged:
        NSLog("Info: \(error)")
        return .RecoverableError
    default:
        NSLog("Error: \(error)") //New error introduced in iOS...?
        return .Fail;
    }
}

在 CloudKit 方法的回调中,您可以像这样使用这个函数:

func loadContacts(retryCountouble = 1) {        
    // Look who of our contact is also using this app.
    EVCloudKitDao.publicDB.allContactsUserInfo({ users in
            EVLog("AllContactUserInfo count = \(users.count)");
            Async.main{
                self.contacts = users
                self.tableView.reloadData()
            }
        }, errorHandler: { error in
            switch EVCloudKitDao.handleCloudKitErrorAs(error, retryAttempt: retryCount) {
            case .Retry(let timeToWait):
                Async.background(after: timeToWait) {
                    self.loadContacts(retryCount + 1)
                }
            case .Fail:
                Helper.showError("Something went wrong: \(error.localizedDescription)")
            default: // For here there is no need to handle the .Success, .Fail and .RecoverableError
                break
            }
    })
}

在我上面的例子中,我使用了一个单独的错误回调处理程序。您也可以在 CloudKit 方法回调中直接调用它。只需先检查是否有错误。

关于ios - 保存 CKRecord 时的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32621306/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap