naga
naga

Reputation: 397

CoreData with Alamofire in Swift 3

I am parsing JSON Data using Alamofire it's working fine. But my aim is to store JSON parsing data in CoreData and show it in tableView. I tried little code but it's not working for me

JSON parsing data and OfflineData.xcdatamodeld

enter image description here

enter image description here

This is my Code:

 var msgdata_store = [Mydata]()
 managedObjextContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

func jsonparsing()
    {

        let Message_dataitems = Mydata(context: managedObjextContext)
        let studentId = "39"
        let params: [String: Any] = ["studentId": studentId]
        let urlString = "http://52.35.124.123/schools/rk/rkapi/api/getmessages"
        guard let url = URL(string: urlString),
            var request = try? URLRequest(url: url, method: .post, headers: nil) else{
                return
        }

        request.httpBody = params.map{ "\($0)=\($1)" }.joined(separator: "&").data(using: .utf8)

        Alamofire.request(request).responseJSON{ response in

            if let result = response.result.value as? [String:Any]
            {

                let arraydata = result["messages"] as? [[String:String]]

                for array_values in arraydata!
                {

                    let content_Vales = array_values["content"]

                    Message_dataitems.content = content_Vales
                }
                do {
                    try self.managedObjextContext.save()

                }catch {
                    print("Could not save data \(error.localizedDescription)")

                }
                self.do_table_refresh()
            }
        }
    }

    func fetchsavedata()
    {
        let presentRequest:NSFetchRequest<Mydata> = Mydata.fetchRequest()

        do {
            msgdata_store = try managedObjextContext.fetch(presentRequest)

            for test in msgdata_store
            {
                let messagecontent = test.content
             print("messagecontent",messagecontent ) as? Any
            }
        }catch {
            print("Could not load data from database \(error.localizedDescription)")
        }
      }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! DetailsTableViewCell

        let row = (indexPath as NSIndexPath).row

        let attendance = msgdata_store[row] as Mydata

        cell.ContentLabel.text = attendance.content

        return cell


    }

    func do_table_refresh(){

        DispatchQueue.main.async(execute: {
            self.Tableview.reloadData()
            return
        })
    }

Mydata+CoreDataProperties,Mydata+CoreDataclass file 

extension Mydata {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Mydata> {
        return NSFetchRequest<Mydata>(entityName: "Mydata")
    }

    @NSManaged public var content: String?

}

@objc(Mydata)
public class Mydata: NSManagedObject {

}

When I run the application, tableView shows only last value. How can I store data in CoreData? please help me.

Upvotes: 0

Views: 1172

Answers (1)

Tom Harrington
Tom Harrington

Reputation: 70956

You're only creating one instance, which is why only one exists.

You create one instance at this line:

let Message_dataitems = Mydata(context: managedObjextContext)

Then later on you have this loop:

for array_values in arraydata!
{

    let content_Vales = array_values["content"]

    Message_dataitems.content = content_Vales
}

Every pass through this loop uses the same instance of Mydata. The first pass assigns a value to content and then every other pass overwrites that value with a new one. You should probably move the line that creates the instance inside the loop, so that you create a new instance every time instead of re-using the same one over and over.

Upvotes: 1

Related Questions