Swift: 将对象直接从JSON api 保存到CoreData rest
Swift: saving objects into CoreData directly from JSON api rest
我需要一些关于 iOS 商店开发的建议:
我需要以最快的方式将数据从 Rest Api 导入我的应用程序的 CoreData。
我想使用 Alamofire + ObjectMapper 或直接使用 AlamofireObjectMapper 将 JSON 结果映射到我的自定义对象模型中,然后将它们保存到 CoreData 中。
我尝试使用 AlamofireObjectMapper,但我没能设置可映射的自定义 NSManagedObject,我用它来将记录保存到 CoreData DB 中,如此处所述
https://github.com/tristanhimmelman/AlamofireObjectMapper
到目前为止,我一直在使用这个指南http://code.tutsplus.com/tutorials/core-data-and-swift-subclassing-nsmanagedobject--cms-25116
创建两个class
MyCustomObjectClass.swift
MyCustomObjectClass+CoreDataProperties.swift
但是,有一种方法可以设置 MyCustomObjectClass 可映射,以便通过一个简单的 AlamofireObjectMapper api 请求我得到 JSON,创建对象并直接存储它们?
其他可能的解决方案?
感谢您的帮助
要将 json 解析为 NSManagedObject
个子类,我推荐 Groot。它需要一些配置,但效果很好。
我还创建了一个名为 AlamofireCoreData 的 cocoapod,它将 Groot 包装到 Alamofire 序列化器,我想你可以用来做你要求的:
// User is a `NSManagedObject` subclass
Alamofire.request(url)
.responseInsert(context: context, type: User.self) { response in
switch response.result {
case let .success(user):
// The user object is already inserted in your context!
case .failure:
// handle error
}
}
希望对您有所帮助。
Api 使用 Swift 中的核心数据调用 4
import UIKit
import CoreData
class ViewController: UIViewController ,UITableViewDelegate,UITableViewDataSource{
var displayDatasssss = [displyDataClass]()
var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
print("hai")
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return displayDatasssss.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell1") as! TableViewCell1
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
cell.label.text = displayDatasssss[indexPath.row].email
let _:AppDelegate = (UIApplication.shared.delegate as! AppDelegate)
let context:NSManagedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let newUser = NSEntityDescription.insertNewObject(forEntityName: "User", into: context) as NSManagedObject
newUser.setValue(cell.label.text, forKey: "name")
do {
try context.save()
} catch {}
print(newUser)
print("Object Saved.")
let myStringValue = cell.label.text
request.predicate = NSPredicate (format: "name == %@", myStringValue!)
do
{
let result = try context.fetch(request)
if result.count > 0
{
let nameData = (result[0] as AnyObject).value(forKey: "name") as! String
print(nameData)
}
}
catch {
//handle error
print(error)
}
return cell
}
@IBAction func tap(_ sender: Any) {
let url = "http://jsonplaceholder.typicode.com/users"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request){(data, response,error)in
if (error != nil){
print("Error")
}
else{
do{
// Array of Data
let fetchData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSArray
for eachData in fetchData {
let eachdataitem = eachData as! [String : Any]
let name = eachdataitem["name"]as! String
let username = eachdataitem["username"]as! String
let email = eachdataitem["email"]as! String
self.displayDatasssss.append(displyDataClass(name: name, username: username,email : email))
}
self.tableView.reloadData()
}
catch{
print("Error 2")
}
}
}
task.resume()
}
}
class displyDataClass {
var name : String
var username : String
var email : String
init(name : String,username : String,email :String) {
self.name = name
self.username = username
self.email = email
}
}
我需要一些关于 iOS 商店开发的建议: 我需要以最快的方式将数据从 Rest Api 导入我的应用程序的 CoreData。
我想使用 Alamofire + ObjectMapper 或直接使用 AlamofireObjectMapper 将 JSON 结果映射到我的自定义对象模型中,然后将它们保存到 CoreData 中。
我尝试使用 AlamofireObjectMapper,但我没能设置可映射的自定义 NSManagedObject,我用它来将记录保存到 CoreData DB 中,如此处所述
https://github.com/tristanhimmelman/AlamofireObjectMapper
到目前为止,我一直在使用这个指南http://code.tutsplus.com/tutorials/core-data-and-swift-subclassing-nsmanagedobject--cms-25116
创建两个class
MyCustomObjectClass.swift
MyCustomObjectClass+CoreDataProperties.swift
但是,有一种方法可以设置 MyCustomObjectClass 可映射,以便通过一个简单的 AlamofireObjectMapper api 请求我得到 JSON,创建对象并直接存储它们?
其他可能的解决方案?
感谢您的帮助
要将 json 解析为 NSManagedObject
个子类,我推荐 Groot。它需要一些配置,但效果很好。
我还创建了一个名为 AlamofireCoreData 的 cocoapod,它将 Groot 包装到 Alamofire 序列化器,我想你可以用来做你要求的:
// User is a `NSManagedObject` subclass
Alamofire.request(url)
.responseInsert(context: context, type: User.self) { response in
switch response.result {
case let .success(user):
// The user object is already inserted in your context!
case .failure:
// handle error
}
}
希望对您有所帮助。
Api 使用 Swift 中的核心数据调用 4
import UIKit
import CoreData
class ViewController: UIViewController ,UITableViewDelegate,UITableViewDataSource{
var displayDatasssss = [displyDataClass]()
var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
print("hai")
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return displayDatasssss.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell1") as! TableViewCell1
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
cell.label.text = displayDatasssss[indexPath.row].email
let _:AppDelegate = (UIApplication.shared.delegate as! AppDelegate)
let context:NSManagedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let newUser = NSEntityDescription.insertNewObject(forEntityName: "User", into: context) as NSManagedObject
newUser.setValue(cell.label.text, forKey: "name")
do {
try context.save()
} catch {}
print(newUser)
print("Object Saved.")
let myStringValue = cell.label.text
request.predicate = NSPredicate (format: "name == %@", myStringValue!)
do
{
let result = try context.fetch(request)
if result.count > 0
{
let nameData = (result[0] as AnyObject).value(forKey: "name") as! String
print(nameData)
}
}
catch {
//handle error
print(error)
}
return cell
}
@IBAction func tap(_ sender: Any) {
let url = "http://jsonplaceholder.typicode.com/users"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request){(data, response,error)in
if (error != nil){
print("Error")
}
else{
do{
// Array of Data
let fetchData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSArray
for eachData in fetchData {
let eachdataitem = eachData as! [String : Any]
let name = eachdataitem["name"]as! String
let username = eachdataitem["username"]as! String
let email = eachdataitem["email"]as! String
self.displayDatasssss.append(displyDataClass(name: name, username: username,email : email))
}
self.tableView.reloadData()
}
catch{
print("Error 2")
}
}
}
task.resume()
}
}
class displyDataClass {
var name : String
var username : String
var email : String
init(name : String,username : String,email :String) {
self.name = name
self.username = username
self.email = email
}
}