JSONDecoder将JSON数据保存到CoreData中而无需循环

时间:2019-02-16 07:59:27

标签: ios urlsession jsondecoder

我仅在2周前开始了我的iOS旅程,此刻我面对一堵砖墙,我需要将API响应直接保存到CoreData中,目前,我必须在解码后循环我的对象,这样我才能单独得出这些值并保存它们。

有没有办法完全不用循环?

让我在下面向您展示我已经完成的工作:

我将结构命名为Example

struct Example: Codable {
    let data:[MyDataClass]

    enum CodingKeys: String, CodingKey {
        case data
    }
}

struct MyDataClass: Codable {
    let name: String
    let age: String
    let gender: String

    enum CodingKeys: String, CodingKey {
        case name
        case age
        case gender
    }
}

我在下面也有我的URLSession代码:

let parameters = ["page": 1] as [String : Any]
        let jsonData = try? JSONSerialization.data(withJSONObject: parameters)

        let url = URL(string: "http://example.com")
        var request = URLRequest(url: url!)
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST" //set http method as POST
        request.httpBody = jsonData

        let task = URLSession.shared.dataTask(with: request) {(data, response, error) in
            guard error == nil else {
                print("returning error")
                return
            }
            guard let content = data else {
                print("not returning data")
                return
            }
            do {

                if let httpResponse = response as? HTTPURLResponse {
                    if(httpResponse.statusCode == 200){
                        let decoded = try JSONDecoder().decode(Example.self, from: content)

                        // Currently I am looping the data and saving it,
                        // But I want to save it directly with JSON.

                        let list = decoded.data.MyDataClass
                        if(!list.isEmpty){
                            for index in 0...list.count-1 {
                                    // call save method here
                            }
                        }


                    }
                }

            } catch {
                print("Got an Error", error.localizedDescription)
            }
        }
        task.resume()

我还有下面的方法,当我循环时,它实际上保存了我的数据。

func saveMyList(name: String,
                         age: Int,
                         gender: String) {

        guard let appDelegate =
            UIApplication.shared.delegate as? AppDelegate else {
                return
        }

        let managedContext = appDelegate.persistentContainer.viewContext
        let entity = NSEntityDescription.entity(forEntityName: "ExampleEntity", in: managedContext)!
        let myList = NSManagedObject(entity: entity, insertInto: managedContext)
        myList.setValue(name, forKeyPath: "name")
        myList.setValue(age, forKeyPath: "age")
        myList.setValue(gender, forKeyPath: "gender")
        do {
            try managedContext.save()
        } catch let error as NSError {
            print("Could not save list. \(error), \(error.userInfo)")
        }
    }

我对此并不陌生,所以请不要提供任何信息。我需要有人来指引我正确的方向,我在网上看到的大多数教程要么太高级,要么做了不同的事情。

0 个答案:

没有答案