将文本段落(包括换行符)存储在云包中并查询

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

我还有一个新手问题。希望你们中的一位编程大师可以帮助我。

我正在尝试从 CloudKit 中获取多段文本(例如一篇新闻文章)。我不知道如何格式化文本以使其包含换行符。有人告诉我应该在 CloudKit 记录上使用 CKAsset 而不是字符串,但我不明白它应该如何格式化。

任何人都可以帮助我进一步了解这一点吗?

提前致谢。

\n 作为新行标识符是否足够? CKAsset 是必经之路,您只需要:

  • 创建文件
  • 使用文件 url
  • 创建资产
  • 保存到数据库
  • 之后删除临时文件。

当您从 CloudKit 获取记录时:

  • 访问它的文件路径
  • 使用NSFileManager
  • 加载数据
  • 解码数据(这里用的是NSString,很坑,但不知道其他什么办法)

保存记录:

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)
        }
    }
}

加载记录:

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)
            }
        }
    }
}

记得适当处理错误,这只是一个展示示例代码。