Ich habe eine Liste von Kategorien, die mein Benutzer auswählen kann. Da ich neue Kategorien hinzufügen möchte, ohne ein neues Update senden zu müssen, möchte ich die neuen Kategorien jedes Mal von meinem Server laden, wenn ein Benutzer die App startet. Ich habe diesen Code entwickelt, aber jedes Mal, wenn er läuft, fügt er die gleichen Kategorien hinzu.Kerndaten mit Server synchronisieren - gleiche Objekte mehrfach hinzugefügt
func loadDealCategory(){
let myUrl = NSURL(string: "\(ipAddress)/v1.0/dealCategory.php")
let request = NSMutableURLRequest(URL: myUrl!)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
{ data, response, error in
if error != nil {
print("error\(error)")
}else{
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSArray
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
for jsonDictionary in json {
// listing of columns in JSON seed file
let categoryDescription = jsonDictionary.valueForKey("category_description") as! String
print(categoryDescription)
let newCategory = NSEntityDescription.insertNewObjectForEntityForName("Categories", inManagedObjectContext: managedContext)
newCategory.setValue(categoryDescription, forKey: "category_description")
// I tried also format: "category_description = %@"
let fetchRequest = NSFetchRequest(entityName: "Categories")
fetchRequest.predicate = NSPredicate(format: "category_description LIKE %@", categoryDescription)
do {
let fetchResults = try managedContext.executeFetchRequest(fetchRequest)
print(fetchResults)
if fetchResults.count == 0{
do {
try managedContext.save()
//5
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
}else{
print("\(categoryDescription) already exist!")
}
} catch let error as NSError {
// failure
print("Fetch failed: \(error.localizedDescription)")
}
}
} catch{
print("something went wrong loading json")
}
}
}
task.resume()
}
- ist ok es, es in
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {