iosswiftofflinereachability

How to save data offline using coredata, and if network comes(online) send the saved data to the API?


How to save data in offline using coredata, and if network comes(online) send the saved data to the API?

This is the code to save data:

func savePSaveInfo(cId: String, pId:String, createdBy:String, agep:String, languageId:String, emailId:String, mobileNumber:String,backendUpdate: Bool)
{    
    let nameObj = NSEntityDescription.insertNewObject(forEntityName: "SaveInfo", into: context!) as! SaveInfo

    nameObj.cId = cId
    nameObj.pId = pId
    nameObj.createdBy = createdBy
    nameObj.agep = agep
    nameObj.languageId = languageId
    nameObj.emailId = emailId
    nameObj.mobileNumber = mobileNumber
    nameObj.backendUpdate = backendUpdate    

    do{
        try context!.save()
    }catch{
        print("not saved")
    }
}

Solution

  • For inserting value in core data, I am sharing a example , you can set according to you data.

    Step 1 :- Set the entity like this enter image description here

    Step 2:-

    //MARK:- FOR CREATING NEW DATA
        func createData(){
    
            //As we know that container is set up in the AppDelegates so we need to refer that container.
            guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
    
            //We need to create a context from this container
            let managedContext = appDelegate.persistentContainer.viewContext
    
            //Now let’s create an entity and new user records.
            let userEntity = NSEntityDescription.entity(forEntityName: "User", in: managedContext)!
    
            //final, we need to add some data to our newly created record for each keys using
    
    
            let user = NSManagedObject(entity: userEntity, insertInto: managedContext)
            user.setValue(txtFldUsername.text!, forKeyPath: "username")
            user.setValue(txtFldEmail.text!, forKey: "email")
            user.setValue(txtFldPassword.text!, forKey: "password")
    
            retrieveData()
            //Now we have set all the values. The next step is to save them inside the Core Data
    
            do {
                try managedContext.save()
    
            } catch let error as NSError {
                print("Could not save. \(error), \(error.userInfo)")
            }
        }
    

    Stop 3:- For fetching data

     //MARK:- FOR RETRIEVING OR FETCHING THE DATA
        func retrieveData() {
    
            //As we know that container is set up in the AppDelegates so we need to refer that container.
            guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
    
            //We need to create a context from this container
            let managedContext = appDelegate.persistentContainer.viewContext
    
            //Prepare the request of type NSFetchRequest  for the entity
            let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
    
            do {
                let result = try managedContext.fetch(fetchRequest)
                arrUserDetails.removeAll()
                for data in result as! [NSManagedObject] {
                    print(data.value(forKey: "username") as! String)
                    arrUserDetails.append(userData(username: (data.value(forKey: "username") as! String), email: (data.value(forKey: "email") as! String), password: (data.value(forKey: "password") as! String)))
                }
                tblView.reloadData()
    
            } catch {
    
                print("Failed")
            }
        }
    

    Still there is any issue , let me know about the query