Swift: saving objects into CoreData directly from JSON api rest
Solution 1
To parse json to NSManagedObject
subclasses, I recommend Groot. It requires a little configuration, but it works great.
I also created a cocoapod called AlamofireCoreData, that wraps Groot into a Alamofire serializer, I think you can use to do exactly what you ask for:
// 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
}
}
Hope it can help you.
Solution 2
Api call with core data in 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
}
}
dayroma
Updated on June 14, 2022Comments
-
dayroma almost 2 years
I'd need some suggestions about iOS store developing: I need to import data from Rest Api into CoreData of my application in the fastest way possible.
I would like to use Alamofire + ObjectMapper or directly AlamofireObjectMapper to map JSON results into my custom objects model and then save them into CoreData.
I tried to use AlamofireObjectMapper but I don't manage to set Mappable custom NSManagedObject I use to save record into CoreData DB, as explained here
https://github.com/tristanhimmelman/AlamofireObjectMapper
Until now, I used this guide http://code.tutsplus.com/tutorials/core-data-and-swift-subclassing-nsmanagedobject--cms-25116
to create two class
MyCustomObjectClass.swift
MyCustomObjectClass+CoreDataProperties.swift
but, there is a way to set MyCustomObjectClass mappable so that with a simple AlamofireObjectMapper api request I get JSON, create objects and store them directly?
Other possible solutions?
Thank you for help