Q:

Obtaining CKAsset URL without downloading data

I'm using CloudKit in my app as a way to persist data remotely. One of my records has an CKAsset property that holds an image. When I'm fetching the records, I realized that it's taking so much time to finish the query. After multiple testings, I concluded that when you query records, CloutKit downloads the entire Asset file with the record object. Hence, when you obtain the Asset from the record object and request it's fileURL, it gives you a local file path URL and not an HTTP kind of URL. This is as issue to me because you have to let the user wait so much time for the entire records to be downloaded (with their associated images) before the query ends. Coming from a Parse background, Parse used to give you the HTTP URL and the query is fast enough to load the UI with the objects while loading the images async. My question is, how can I achieve what Parse does? I need to restrict the queries from downloading the Assets data and obtain a link to load the images asynchronously. 

A:

You can use CloudKit JavaScript for accessing url of asset. Here is an example;
(Used Alamofire and SwiftyJSON)
func testRecordRequest() -> Request {
    let urlString = "https://api.apple-cloudkit.com/database/1/" + Constants.container + "/development/public/records/query?ckAPIToken=" + Constants.cloudKitAPIToken
    let query = ["recordType": "TestRecord"]
    return Alamofire.request(.POST, urlString, parameters: ["query": query], encoding: .JSON, headers: nil)
}

JSON response contains a "downloadURL" for the asset.
"downloadURL": "https://cvws.icloud-content.com/B/.../${f}?o=AmVtU..."

"${f}" seems like a variable so change it to anything you like.
let downloadURLString = json["fields"][FieldNames.image]["value"]["downloadURL"].stringValue
let recordName = json["recordName"].stringValue
let fileName = recordName + ".jpg"
let imageURLString = downloadURLString.stringByReplacingOccurrencesOfString("${f}", withString: fileName)

And now we can use this urlString to create a NSURL and use it with any image&cache solutions such as Kingfisher, HanekeSwift etc.
(You may also want to save image type png/jpg)

