Reputation: 267
I have an optional image in the cloudkit DB(checked DB and the image is there in cases where I added it in my testing). I have created a class that initializes the record fields into variables I use in my tableview. I have a custom cell as well. But the image won't display in my custom tableview cell. I don't know if having an optional image in a tableview image is causing a problem or if there's an issue with my code/settings in cloudkit.
Any help is greatly appreciated, as I've been stuck for over a week and there's little to nothing online about this.
Here's my class code:
var feedResults = [UserPosts]()
class UserPosts {
var record: CKRecord
var description: String
var username: String
//var image: CKAsset? // tried also initializing the CKAsset separately
var postPic: UIImage?
init(record: CKRecord) {
self.record = record
self.description = record.objectForKey("description") as String
self.username = record.objectForKey("username") as String
// self.image = record.objectForKey("postPic") as? CKAsset
if var pic = record.objectForKey("postPic") as CKAsset! {
self.postPic = UIImage(contentsOfFile: pic.fileURL.path!)
// below is the other way I've seen it done.
// var url = pic.fileURL!
// var imageData = NSData(contentsOfFile: url.path!)
// self.postPic = UIImage(data: imageData!)
}
}
}
Here's my tableview code:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as TableViewCell
let record = feedResults[indexPath.row]
cell.postDescription.text = record.description
cell.userName.text = record.username
if record.postPic != nil {
cell.postPic.image = record.postPic!
}
return cell
}
Also I've seen a couple ways of pulling a CKAsset into a UIImage. The first way, is how I saw Apple do it in their CloudKitAtlas project. Although I'm not well versed in Obj-C, I think I followed it correctly - CloudKitAtlas Example
I've also seen it done using NSData(contentOFFile:) and UIImage(data:), as shown in this post here: SO CKAsset Example
Upvotes: 4
Views: 1438
Reputation: 86
You can display the image from the CKAsset like this:
var img = record.valueForKey("Picture") as? CKAsset
cell.imageView?.image = UIImage(contentsOfFile: img!.fileURL.path!)
Hope this helps!
Upvotes: 1
Reputation: 13127
Try doing it without the .paths and using contentsOfURL. This is how I do this (within your if for the CKAsset):
if var data = NSData(contentsOfURL: pic!.fileURL) {
self.postPic = UIImage(data: data!)!
}
And besides that... You do a dequeueReusableCellWithIdentifier but don't check if it returns nil. You should create a new cell instance If it was nil
Upvotes: 3