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

问题描述 投票:3回答:2

我需要一些关于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可映射,以便使用简单的AlamofireObjectMapper api请求获取JSON,创建对象并直接存储它们?

其他可能的方案?

谢谢你的帮助

json swift core-data alamofire nsmanagedobject
2个回答
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
投票

在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
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.