将 RestKit 和 CoreData 与 Swift 一起使用

Using RestKit and CoreData with Swift

我尝试将 Swift 中的 RestKit 与桥接头一起使用。我有一个 JSON 文件 url "http://local:8888/api/0.1/jobs"

{"data":[{"id": "1", "name": "job1",..},{"id": "2", "name": "job2",...},...]}

JSON 文件有 6 个元素作业。我为 CoreData 创建了 Job 实体并生成了 Job class。

我是这样设置 RestKit 的:

func setupRestKit() {
    var manager = RKObjectManager(baseURL: NSURL(string: "http://local:8888/api/0.1/"))

    RKObjectManager.setSharedManager(manager)

    var managedObjectModel = NSManagedObjectModel.mergedModelFromBundles(nil)
    var managedObjectStore = RKManagedObjectStore(managedObjectModel: managedObjectModel)
    manager.managedObjectStore = managedObjectStore

    RKManagedObjectStore.setDefaultStore(manager.managedObjectStore)

    var jobMapping = RKEntityMapping(forEntityForName: "Job", inManagedObjectStore: manager.managedObjectStore)

    jobMapping.identificationAttributes = ["id"]
    jobMapping.addAttributeMappingsFromDictionary([
        "id"     : "id",
        "name"      : "name"
    ])

    let responseDescriptor = RKResponseDescriptor(
        mapping: jobMapping,
        method: RKRequestMethod.GET,
        pathPattern: "/jobs",
        keyPath: "data",
        statusCodes: NSIndexSet(index: 200)
    )

    manager.addResponseDescriptor(responseDescriptor)

    managedObjectStore.createPersistentStoreCoordinator()

    let storePath = RKApplicationDataDirectory().stringByAppendingPathComponent("MyApp.sql")

    var persistentStore = managedObjectStore.addSQLitePersistentStoreAtPath(
        storePath,
        fromSeedDatabaseAtPath: nil,
        withConfiguration: nil,
        options: optionsForSqliteStore(),
        error: nil
    )

    managedObjectStore.createManagedObjectContexts()

    managedObjectStore.managedObjectCache = RKInMemoryManagedObjectCache(
        managedObjectContext: managedObjectStore.persistentStoreManagedObjectContext
    )
}

func optionsForSqliteStore() -> NSDictionary {
    return [
        NSInferMappingModelAutomaticallyOption: true,
        NSMigratePersistentStoresAutomaticallyOption: true
    ];
}

并且在 ViewController 中:

override func viewDidLoad() {
    super.viewDidLoad()

    var fetchRequest = NSFetchRequest(entityName: "Job")

    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]

    self.fetchedResultsController = NSFetchedResultsController(
        fetchRequest: fetchRequest,
        managedObjectContext: RKManagedObjectStore.defaultStore().mainQueueManagedObjectContext,
        sectionNameKeyPath: nil,
        cacheName: nil
    )

    self.fetchedResultsController?.delegate = self

    self.fetchedResultsController?.performFetch(nil)

    tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    if let sections = fetchedResultsController?.sections {
        return sections.count
    } else {
        return 0
    }
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if let sections = fetchedResultsController?.sections {
        var sectionInfo: AnyObject = sections[section]
        return sectionInfo.numberOfObjects
    } else {
        return 0
    }
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell

    if let fetchedResults = fetchedResultsController {
        cell.textLabel?.text = fetchedResults.objectAtIndexPath(indexPath).name
    }

    return cell
}

numberOfSectionsInTableView 方法 return 值 0 和 tableView numberOfRowsInSection return 值 0 也是。

我通过翻译 Objective-C 的代码尝试了很多解决方案,因为 Swift 使用 RestKit 的例子并不多。

我可以使用 SwiftyJson 框架访问 JSON 中的数据,我还通过自己在 CoreData 数据库中的存储元素验证了我的配置。

我想获得我用这个简单的 RestApi 创建的 6 个作业,并将其打印在 tableView.

我想我在配置过程中做错了什么,但我不知道是什么。

正如大卫所说,我忘记从服务器获取(谢谢)。

// I just need to map correctly the path
var manager = RKObjectManager(baseURL: NSURL(string: "http://local:8888/api/0.1/jobs"))

[...]
var persistentStore = managedObjectStore.addSQLitePersistentStoreAtPath(
    storePath,
    fromSeedDatabaseAtPath: nil, // Set-up this
    withConfiguration: nil,
    options: optionsForSqliteStore(),
    error: nil
)

managedObjectStore.createManagedObjectContexts()

managedObjectStore.managedObjectCache = RKInMemoryManagedObjectCache(
    managedObjectContext: managedObjectStore.persistentStoreManagedObjectContext
)
manager.getObjectsAtPath(
    "", // Add path
    parameters: nil,
    success: nil,
    failure: nil
)

然后我得到了我认为的项目。