CKQueryOperation error: This operation has been rate limited

CKQueryOperation error: This operation has been rate limited

客户端在使用 CKQueryOperation 下载记录时收到来自 CloudKit 的 error 1298: This operation has been rate limited 错误,只有一次,在 Apple 审查期间。我该如何解决这个问题?

这里是代码,没什么特别的:

let query = CKQuery(recordType: "Movie", predicate: NSPredicate(format: "creationDate > %@", d!))
let qo = CKQueryOperation(query: query)
let fb: (CKRecord!) -> () = {record in

    temporaryContext.performBlockAndWait({

        let fr = NSFetchRequest(entityName: "Movie")
        fr.predicate = NSPredicate(format: "recordName = %@", record.recordID.recordName)

        let a = temporaryContext.executeFetchRequest(fr, error: nil) as! [Movie]
        if a.count == 0 {

            let m = NSEntityDescription.insertNewObjectForEntityForName("Movie", inManagedObjectContext: temporaryContext) as! Movie
            m.title = record.valueForKey("title") as! String
            m.image = (record.valueForKey("image") as! CKAsset).fileURL.description
            m.imageSize = Int32(record.valueForKey("imageSize") as! Int)
            m.recordName = record.recordID.recordName
        }
    })
}

let c: ()->() = {

    temporaryContext.performBlockAndWait({
        let success = temporaryContext.save(nil)
    })

    Utility.managedObjectContext().performBlockAndWait({

        let success = Utility.managedObjectContext().save(nil)
    })

    NSUserDefaults.standardUserDefaults().setBool(true, forKey: "moviesDownloaded")
    NSUserDefaults.standardUserDefaults().synchronize()

    dispatch_semaphore_signal(self.sema)
}

let cb: (CKQueryCursor!, NSError!) -> () = {cursor, error in

    if error == nil {

        if cursor != nil {

            let qo2 = Utility.qo(cursor, recordFetchedBlock: fb, completion: c)
            publicDatabase.addOperation(qo2)

        } else {

            c()
        }

    } else {
        Utility.log("error 1298: \(error.localizedDescription)")

        dispatch_sync(dispatch_get_main_queue(), {
            self.status.backgroundColor = UIColor.orangeColor()
        })

        NSThread.sleepForTimeInterval(0.5)

        dispatch_semaphore_signal(self.sema)
    }
}

qo.recordFetchedBlock = fb
qo.queryCompletionBlock = cb
publicDatabase.addOperation(qo)

dispatch_semaphore_wait(self.sema, DISPATCH_TIME_FOREVER)

我尝试将整个代码放入一个循环中,例如:

for i in 1 ... 2 {
var rateLimited = false

...
if error == nil {

} else {

    NSThread.sleepForTimeInterval(3)
    rateLimited = true
}
...

if !rateLimited {

     break
}
}

你觉得行吗?

如果你得到 CKErrorRequestRateLimited 错误将在错误的 userInfo 字典中有一个 CKErrorRetryAfterKey 键。在重试操作之前,您应该至少等待该时间。

休眠等待是个坏主意,因为它会导致您的应用程序意外挂起,尤其是当该代码在您的主线程上运行时。使用 dispatch_afterNSTimer 重新发送您的操作。

如果您没有登录您的 iCloud 帐户,您也会遇到此错误。