I am writing an IOS App which receives data from the user which I want to store in two different data models with different purposes:
I want the User to be able to work without an internet connection.
Therefore I am trying to pass-on a newly created instance of the Reconciliation-ManagedObject (=reconTask) after it has been saved to a 2nd function (= apiCheckCodes). Unfortunately this is not working and I am thankful for any help. This is the code:
`func setReconciliationList()->Void {
let appDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
let managedObjectContext = appDelegate.managedObjectContext
let entityDescription = NSEntityDescription.entityForName("ReconciliationModel", inManagedObjectContext: managedObjectContext!)
let reconTask = ReconciliationModel(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext!)
reconTask.reconStatus = false
reconTask.reconType = 2
reconTask.reconUser = inputTextField.User
appDelegate.saveContext()
// if Internet available ...
redeemCodes(reconTask.managedObjectContext!)
}`
func apiCheckCodes(context: context: NSManagedObjectContext)-> Void {
let fetchRequest = NSFetchRequest(entityName: "ReconciliationModel")
var requestError: NSError?
let response = context.executeFetchRequest(fetchRequest, error: &requestError) as [ReconciliationModel!]
let reconObject = (response as NSArray).lastObject as ReconciliationModel
var request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:3000/apicodecheck")!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var params = [
"user" : ReconObject.user,
"status" : ReconObject.status,
"programGoal" : String(ReconObject.programGoal)
]
var error: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &error)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
// API Redeem Post request
var task = session.dataTaskWithRequest(request, completionHandler: { (data, response, err) -> Void in
var conversionError: NSError?
var jsonDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableLeaves, error: &conversionError) as? NSDictionary
})
task.resume()
}
Edit: I found a way around it with a fetchRequest in the 2nd function (see above). Is this the only solution?
I found what I was doing wrong and therefore the work-around solution I described in my edit above with fetchRequest is no longer needed.
I was defining the 2nd function (= apiCheckCodes) wrongly with "as ReconciliationModel" instead of like this:
func verifiyScannedCode(reconObject: ReconciliationModel) {...}
Now I can call the this function with the newly created ManagedObject as a Parameter
verifiyScannedCode(reconTask)