Search code examples
iosswiftcloudkit

Store paragraphs of text (including line breaks) in cloud kit and query


I have another newbie question. Hopefully one of you programming gurus can help me with it.

I'm trying to fetch multiple paragraphs of text (e.g. a news article) from CloudKit. I don't know how to format the text so that it includes a line break. I've been told that I should use CKAsset instead of a String on the CloudKit record, but I don't understand how it's supposed to be formatted.

Can anyone help me understand this more?

Thanks in advance.


Solution

  • Would it suffice to have \n as the new line identifier? CKAsset is the way to go, you just need to:

    • create the file
    • create asset with the file's url
    • save it to database
    • remove the temp file afterwards.

    When you get the record from CloudKit:

    • access it's file path
    • load the data using NSFileManager
    • decode the data (this uses NSString, which is a bore, but don't know any other way)

    Save Record:

    let str = "sample \n string save to file"
    if let url = NSURL(fileURLWithPath: NSTemporaryDirectory())?.URLByAppendingPathComponent("tempFile", isDirectory: false) {
        if str.writeToURL(url, atomically: true, encoding: NSUTF8StringEncoding, error: nil) {
            let asset = CKAsset(fileURL: url)
            let record = CKRecord(recordType: "TextAsset")
            record.setValue(asset, forKey: "text")
            CKContainer.defaultContainer().publicCloudDatabase.saveRecord(record) { savedRecord, error in
                if error != nil {
                    println(error)
                } else {
                    println(savedRecord)
                }
                // do this in completion closure, otherwise the file gets deleted before uploading
                NSFileManager.defaultManager().removeItemAtURL(url, error: nil)
            }
        }
    }
    

    Load record:

    let predicate = NSPredicate(value: true)
    let query = CKQuery(recordType: "TextAsset", predicate: predicate)
    CKContainer.defaultContainer().publicCloudDatabase.performQuery(query, inZoneWithID: nil) { queryRecords, error in
        if let records = queryRecords {
            for record in records {
                let asset = record.valueForKey("text") as! CKAsset
                if let content = NSFileManager.defaultManager().contentsAtPath(asset.fileURL.path!) {
                    let text = NSString(data: content, encoding: NSUTF8StringEncoding)
                    println(text)
                }
            }
        }
    }
    

    Remember to handle errors appropriately, this is just a showcase sample code.