我尝试在 Swift 中将 RestKit 与 Bridging Header 结合使用。我有一个 URL 为“http://local:8888/api/0.1/jobs”的 JSON 文件
{"data":[{"id": "1", "name": "job1",..},{"id": "2", "name": "job2",...},...]}
JSON 文件有 6 个元素 Job.我为 CoreData 创建了 Job 实体并生成了 Job 类。
我是这样设置 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 方法返回值0,tableView numberOfRowsInSection 也返回值0。
我通过翻译 Objective-C 的代码尝试了很多解决方案,因为 Swift 使用 RestKit 的例子并不多。
我能够使用 SwiftyJson 框架访问 JSON 中的数据,我还通过自己在 CoreData 数据库中的存储元素验证我的配置。
我想获得我用这个简单的 RestApi 创建的 6 个作业,并将其打印在 tableView 中。
我想我在配置过程中做错了什么,但我不知道是什么。
最佳答案
正如 David 所说,我忘记从服务器获取数据(谢谢)。
// 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
)
然后我得到了我 View 中的项目。
关于ios - 在 Swift 中使用 RestKit 和 CoreData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28028177/