我正在编写一个IOS应用程序,它接收来自用户的数据,我希望将这些数据存储在两个不同用途的数据模型中:
我希望用户能够在没有互联网连接的情况下工作。
因此,我尝试在将新创建的Reconciliation-ManagedObject(= reconTask)实例保存到第二个函数(= apiCheckCodes)后传递它。不幸的是,这不起作用,我感谢任何帮助。这是代码:
`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()
}
编辑: 我在第二个函数中找到了一个使用fetchRequest的方法(参见上文)。这是唯一的解决方案吗?