Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
- let cell = tableView.dequeueReusableCell(withIdentifier: "BookCell", for: indexPath) as! BookTableViewCell
- // Configure the cell...
- let book = books[indexPath.row]
- cell.nameLabel.text = book.object(forKey: "name") as? String
- cell.typeLabel.text = book.object(forKey: "genre") as? String
- cell.isbnLabel.text = book.object(forKey: "isbn") as? String
- // Set the default book image
- cell.thumbnailImageView.image = UIImage(named: "photo_album")
- // Check if the book image is stored in cache
- if let imageFileURL = imageCache.object(forKey: book.recordID) {
- // Fetch image from cache
- if let imageData = try? Data.init(contentsOf: imageFileURL as URL) {
- cell.thumbnailImageView.image = UIImage(data: imageData)
- }
- } else {
- // Fetch Image from Cloud in background
- let publicDatabase = CKContainer.default().publicCloudDatabase
- let fetchBookImageRecordsOperation = CKFetchRecordsOperation(recordIDs: [book.recordID])
- fetchBookImageRecordsOperation.desiredKeys = ["image"]
- fetchBookImageRecordsOperation.queuePriority = .veryHigh
- fetchBookImageRecordsOperation.perRecordCompletionBlock = { (record, recordID, error) -> Void in
- if let error = error {
- print("Failed to get book image: \(error.localizedDescription)")
- return
- }
- if let bookRecord = record {
- OperationQueue.main.addOperation() {
- if let image = bookRecord.object(forKey: "image") {
- let bookImageAsset = image as! CKAsset
- if let imageData = try? Data.init(contentsOf: bookImageAsset.fileURL) {
- cell.thumbnailImageView.image = UIImage(data: imageData)
- }
- // Add the book image URL to cache
- self.imageCache.setObject(bookImageAsset.fileURL as NSURL, forKey: book.recordID)
- }
- }
- }
- }
- publicDatabase.add(fetchBookImageRecordsOperation)
- }
- return cell
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement