0

I'm pretty new to swift, so please try to bear with me.

I'm currently able to download CKRecords and insert them into an array, "birdFacts". Each record includes a few strings, an image (CKAsset), a date, and an int. When they initially download from iCloud, everything works fine.

Everything is saving as expected, except the image. When I reload the data, the asset doesn't show up.

Here is my code to load saved data:

    if let savedFacts = loadFacts() {
        birdFacts = savedFacts
        print("successfully loaded saved bird facts")
    }

func loadFacts() -> [CKRecord]? {
    return NSKeyedUnarchiver.unarchiveObjectWithFile(BirdFact.ArchiveURL.path!) as? [CKRecord]
}

This is my code to save the array:

func saveFacts() {
    let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(birdFacts, toFile: BirdFact.ArchiveURL.path!)
    if !isSuccessfulSave {
        print("Failed to save bird facts")
    }
}

This is within my custom class definition file:

import UIKit
import CloudKit

class BirdFact: NSObject, NSCoding {
//MARK: PROPERTIES
var birdName: String

var photo: CKAsset

var birdFact: String

var date: NSDate

var sortingDate: Int

//MARK: TYPES
struct PropertyKey {
    static let namekey = "name"
    static let photokey = "photo"
    static let factkey = "fact"
    static let datekey = "date"
    static let sortingDatekey = "sortingDate"
}

//MARK: INITIALIZATION

init?(birdName: String, photo: CKAsset, birdFact: String, date: NSDate, sortingDate: Int){
    //init stored props
    self.birdName = birdName
    self.photo = photo
    self.birdFact = birdFact
    self.date = date
    self.sortingDate = sortingDate

    super.init()

    if birdName.isEmpty || birdFact.isEmpty {
        return nil
    }
}

//MARK: NSCODING
func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(birdName, forKey: PropertyKey.namekey)
    aCoder.encodeObject(photo, forKey: PropertyKey.photokey)
    aCoder.encodeObject(birdFact, forKey: PropertyKey.factkey)
    aCoder.encodeObject(date, forKey: PropertyKey.datekey)
    aCoder.encodeObject(sortingDate, forKey: PropertyKey.sortingDatekey)
}

required convenience init?(coder aDecoder: NSCoder) {
    let birdName = aDecoder.decodeObjectForKey(PropertyKey.namekey) as! String
    let photo = aDecoder.decodeObjectForKey(PropertyKey.photokey) as! CKAsset
    let birdFact = aDecoder.decodeObjectForKey(PropertyKey.factkey) as! String
    let date = aDecoder.decodeObjectForKey(PropertyKey.datekey) as! NSDate
    let sortingDate = aDecoder.decodeObjectForKey(PropertyKey.sortingDatekey) as! Int

    self.init(birdName: birdName, photo: photo, birdFact: birdFact, date: date, sortingDate: sortingDate)
}

//MARK: ARCHIVING PATHS
static let DocumentsDirectory = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("BirdFacts")

}

I'm saving whenever I finish downloading and sorting the records. Any idea what is going wrong?

EDIT: Included CloudKit query. I should note that I never save anything to iCloud, only download existing records.

func allprevFacts(date: String, olddate: Int){
    act.startAnimating()
    let container = CKContainer.defaultContainer()
    let publicDB = container.publicCloudDatabase
    //let factPredicate = NSPredicate(format: "recordID = %@", CKRecordID(recordName: date))
    let factPredicate = NSPredicate(format: "date <= %@", NSDate())
    let query = CKQuery(recordType: "BirdFacts", predicate: factPredicate)
    publicDB.performQuery(query, inZoneWithID: nil) { (results, error) -> Void in
        if error != nil {
            print(error)
        }
        else {
            dispatch_async(dispatch_get_main_queue()){
                //print(results)
                var count = 0
                var sortedresults = [Int]()
                for result in results! {
                    var b = result.valueForKey("sortingDate") as! Int
                    sortedresults.append(b)
                }
                print(sortedresults)
                while count < sortedresults.count {
                    if sortedresults[count] <= olddate {
                        sortedresults.removeAtIndex(count)
                    }
                    else {
                        count = count + 1
                    }
                }
                print(sortedresults)
                while sortedresults.count > 0 {
                    var d: Int = 0
                    let a = sortedresults.maxElement()
                    print(a)
                    while d < sortedresults.count{
                        if sortedresults[d] == a {
                            sortedresults.removeAtIndex(d)
                            self.birdFacts.append(results![d])
                            self.tableFacts.reloadData()
                            self.tableFacts.hidden = false
                        }
                        d = d + 1
                        print(d)
                    }
                }
                self.saveFacts()
                print("saving bird facts")
                self.tableFacts.hidden = false
            }
        }
    }
    act.stopAnimating()
Alex
  • 141
  • 2
  • 10
  • Where are your CloudKit functions? Saving and Loading. – rmickeyd Jun 01 '16 at 20:58
  • They are at the bottom of the same file where I fetch new facts and append them to the array (TableViewController.swift) – Alex Jun 02 '16 at 04:04
  • I do not see where you query or save to Cloud via cloudkit. Please post. – rmickeyd Jun 02 '16 at 04:37
  • Just added my function to download records--I never save anything to CloudKit, just to the local drive – Alex Jun 02 '16 at 16:45
  • After doing some tests, I think the images still exist, but the issue is that they aren't displaying on the screen – Alex Jun 02 '16 at 16:53
  • I think you need to save the image locally when you pull it from the cloud. Then find that filepath and cast it to a UIImage before you can view it. – rmickeyd Jun 02 '16 at 17:21
  • When I originally download the file from the cloud, it shows up fine. The issue I run into is trying to re-load the previously downloaded and locally-saved image after quitting the app. – Alex Jun 02 '16 at 17:43

0 Answers0