Swift:直接从JSON api rest将对象保存到CoreData中

时间:2016-06-28 13:13:04

标签: json swift core-data alamofire nsmanagedobject

我需要一些关于iOS商店开发的建议: 我需要以最快的方式将Rest Api中的数据导入到我的应用程序的CoreData中。

我想使用Alamofire + ObjectMapper或直接使用AlamofireObjectMapper将JSON结果映射到我的自定义对象模型中,然后将它们保存到CoreData中。

我尝试使用AlamofireObjectMapper,但我没有设法设置Mappable自定义NSManagedObject,用于将记录保存到CoreData DB中,如此处所述

https://github.com/tristanhimmelman/AlamofireObjectMapper

到目前为止,我使用了本指南http://code.tutsplus.com/tutorials/core-data-and-swift-subclassing-nsmanagedobject--cms-25116

创建两个类

MyCustomObjectClass.swift

MyCustomObjectClass + CoreDataProperties.swift

但是,有一种方法可以将MyCustomObjectClass设置为mappable,以便使用简单的AlamofireObjectMapper api请求获取JSON,创建对象并直接存储它们?

其他可能的解决方案?

感谢您的帮助

2 个答案:

答案 0 :(得分:3)

要将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
        }
}

希望它可以帮到你。

答案 1 :(得分:1)

使用Swift 4中的核心数据进行Api调用

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
   }
}