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

标签 ios swift cloudkit

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

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

谁能帮助我更深入地了解这一点?

提前致谢。

最佳答案

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

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

当您从 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)
            }
        }
    }
}

记住要适本地处理错误,这只是一个展示示例代码。

关于ios - 将文本段落(包括换行符)存储在云包中并查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31813295/

相关文章:

objective-c - 使用从测试方法调用的方法的类的 OCMock

ios - 如何使用swift监控电池电量和状态变化

ios - CloudKit 查询出现奇怪错误

ios - 如何从 cloudkit 接收图像?

objective-c - 如何使用 ASIHTTPRequest 在自定义 UITableViewCell 中显示下载进度?

javascript - 在用户向下滚动时将元素 "up"滑动到另一个元素上,没有固定定位?

ios - 允许在有效的电子邮件地址中使用中文字符。

iOS - Xcode 错误 : cannot attach to process due to System Integrity Protection

swift - 如何从 cellForRowAtIndexPath 更改行高?

swift - NSUbiquitousKeyValueStore 在 Watch OS 3.1.3 上不可用