11/30/2017 - 4:37 AM

Swift - CloudKit - Using asset and location fields

CloudKit provides field types specifically for storing large data files and for fetching records by location. Use these data types to leverage the performance improvements that CloudKit provides for this type of data. You can also fetch records by location. For example, display records on a map in a user-defined region.

See: https://developer.apple.com/library/content/documentation/DataManagement/Conceptual/CloudKitQuickStart/AddingAssetsandLocations/AddingAssetsandLocations.html

01. Store Large Files in CloudKit

You can store large data files in CloudKit using the Asset field type. Assets are owned by the associated 
record, and CloudKit handles garbage collection for you. CloudKit also efficiently uploads and downloads 

In code, the Asset field type is represented by a CKAsset object. This code fragment sets an Asset field 
in an Artwork record to a resource file.

   // Create a URL to the local file
var resourceURL = URL(fileURLWithPath: "…")
if resourceURL {
    var asset = CKAsset(fileURL: resourceURL)
    artworkRecord["image"] = asset

When the record is saved, the file is uploaded to iCloud.

02. Add Location Fields

If your record has an address or other location data, you can save it as a CLLocation object in the record 
and later fetch records by location. For example, your app might display pins representing the records on 
a map.

This code fragment uses the CLGeocoder class to convert a string address to a location object and stores 
it in a record.

var geocoder = CLGeocoder()
geocoder.geocodeAddressString(artwork[kArtworkAddressKey], completionHandler: {(_ placemark: [Any], _ error: Error?) -> Void in
    if error == nil {
        if placemark.count > 0 {
            var placement = placemark[0] as? CLPlacemark
            artworkRecord[kArtworkLocationKey] = placement.location
    else {
        // insert error handling here
    // Save the record to the database

03. Fetch records by location

Once you have location data in your database, you can fetch records by location using a query 
containing a record type, a predicate, and a sort descriptor. The Location field specified in 
the predicate must be indexed for the fetch to succeed.

This code fragment fetches all records whose locations are within 100,000 meters of San Francisco.

// Get the public database object

var publicDatabase: CKDatabase? = CKContainer.default().publicCloudDatabase
    // Create a predicate to retrieve records within a radius of the user's location
var fixedLocation = CLLocation(latitude: 37.7749300 as? CLLocationDegrees ?? CLLocationDegrees(), longitude: -122.4194200 as? CLLocationDegrees ?? CLLocationDegrees())
var radius: CGFloat = 100000
    // meters
var predicate = NSPredicate(format: "distanceToLocation:fromLocation:(location, %@) < %f", fixedLocation, radius)
    // Create a query using the predicate
var query = CKQuery(recordType: "Artwork", predicate: predicate)
// Execute the query
publicDatabase?.perform(query, inZoneWith: nil, completionHandler: {(_ results: [Any], _ error: Error?) -> Void in
    if error != nil {
        // Error handling for failed fetch from public database
    else {
        // Display the fetched records

For Location Services and Maps also see: https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/LocationAwarenessPG/Introduction/Introduction.html#//apple_ref/doc/uid/TP40009497