relations using CoreDatato-many key not allowed here - ios

I am getting a crash related to a core data relationship which is to-many
nueva marca -----><Autos.Marca: 0x7fac604d3250> (entity: Marca; id:
0x7fac604d3300
<x-coredata:///Marca/tB1CE1C53-077E-4402-8E3A-E6C6F147B4672> ; data: {
modelos = (
);
nombre = NIKE; })
Nuevo modelo:::::::: <Autos.Modelo: 0x7fac604d6df0> (entity: Modelo;
id: 0x7fac604d6e50
<x-coredata:///Modelo/tB1CE1C53-077E-4402-8E3A-E6C6F147B4673> ; data:
{
marca = "0x7fac604d3300 <x-coredata:///Marca/tB1CE1C53-077E-4402-8E3A-E6C6F147B4672>";
nombre = "AIRFORCE 1"; }) arreglo Relationship 'modelos' on managed object (0x7fac604d3250) <Autos.Marca: 0x7fac604d3250> (entity:
Marca; id: 0x7fac604d3300
<x-coredata:///Marca/tB1CE1C53-077E-4402-8E3A-E6C6F147B4672> ; data: {
modelos = (
"0x7fac604d6e50 <x-coredata:///Modelo/tB1CE1C53-077E-4402-8E3A-E6C6F147B4673>"
);
nombre = NIKE; }) with objects {(
<Autos.Modelo: 0x7fac604d6df0> (entity: Modelo; id: 0x7fac604d6e50> <x-coredata:///Modelo/tB1CE1C53-077E-4402-8E3A-E6C6F147B4673> ; data:
{
marca = "0x7fac604d3300 <x-coredata:///Marca/tB1CE1C53-077E-4402-8E3A-E6C6F147B4672>";
nombre = "AIRFORCE 1"; }) )} Nuevo Marca <Autos.Marca: 0x7fac604d3250> (entity: Marca; id: 0xd000000000080000
<x-coredata://D8BC4DF2-5A4A-4D3D-A10D-91FE28DABA30/Marca/p2> ; data: {
modelos = (
"0xd000000000080002 <x-coredata://D8BC4DF2-5A4A-4D3D-A10D-91FE28DABA30/Modelo/p2>"
);
nombre = NIKE; }) 2016-05-03 11:21:22.778 Autos[745:17150] *** Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: 'to-many key not allowed here'
*** First throw call stack: ( 0 CoreFoundation 0x000000010bbc7d85 __exceptionPreprocess + 165 1 libobjc.A.dylib
0x000000010d96bdeb objc_exception_throw + 48 2 CoreData
0x000000010b81efff -[NSSQLGenerator newSQLStatementForRequest:ignoreInheritance:countOnly:nestingLevel:nestIsWhereScoped:]
+ 1583 3 CoreData 0x000000010b7117e3 -[NSSQLGenerator newSQLStatementForFetchRequest:ignoreInheritance:countOnly:nestingLevel:nestIsWhereScoped:]
+ 35 4 CoreData 0x000000010b8047b8 -[NSSQLAdapter _statementForFetchRequest:ignoreInheritance:countOnly:nestingLevel:]
+ 344 5 CoreData 0x000000010b71167c -[NSSQLAdapter _newSelectStatementWithFetchRequest:ignoreInheritance:]
+ 316 6 CoreData 0x000000010b7112f6 -[NSSQLCore newRowsForFetchPlan:]
+ 118 7 CoreData 0x000000010b710bac -[NSSQLCore objectsForFetchRequest:inContext:]
+ 524 8 CoreData 0x000000010b710549 -[NSSQLCore executeRequest:withContext:error:]
+ 377 9 CoreData 0x000000010b7f5eaf __65-[NSPersistentStoreCoordinator executeRequest:withContext:error:]_block_invoke
+ 3311 10 CoreData 0x000000010b7ff4dd gutsOfBlockToNSPersistentStoreCoordinatorPerform
+ 189 11 libdispatch.dylib 0x000000010e4043eb _dispatch_client_callout
+ 8 12 libdispatch.dylib 0x000000010e3e8ef5 _dispatch_barrier_sync_f_invoke
+ 393 13 CoreData 0x000000010b7f05d5 _perform
+ 197 14 CoreData 0x000000010b7101b4 -[NSPersistentStoreCoordinator
executeRequest:withContext:error:]
+ 500 15 CoreData 0x000000010b70e973 -[NSManagedObjectContext executeFetchRequest:error:]
+ 579 16 CoreData 0x000000010b7c65f5 -[NSManagedObjectContext executeRequest:error:]
+ 421 17 Autos 0x000000010b652db9 _TFC5Autos14ViewController11viewDidLoadfT_T_
+ 3929 18 Autos 0x000000010b6531f2 _TToFC5Autos14ViewController11viewDidLoadfT_T_
+ 34 19 UIKit 0x000000010c58a984 -[UIViewController loadViewIfRequired]
+ 1198 20 UIKit 0x000000010c58acd3 -[UIViewController view]
...
My view controller code is:
let appDelegado:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let contexto:NSManagedObjectContext = appDelegado.managedObjectContext
let entidadMarca = "Marca"
let entidadModelo = "Modelo"
let modeloNike = "AIRFORCE 1"
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//Conusltando Base de datos
let newMarca = NSEntityDescription.insertNewObjectForEntityForName(entidadMarca, inManagedObjectContext:contexto)
newMarca.setValue("NIKE", forKey: "nombre")
print("nueva marca ----->\(newMarca) \n")
//objeto modelo
let newModelo = NSEntityDescription.insertNewObjectForEntityForName(entidadModelo, inManagedObjectContext:contexto)
newModelo.setValue("AIRFORCE 1", forKey: "nombre")
let entytiModelo = NSEntityDescription.entityForName(entidadMarca, inManagedObjectContext:contexto)
let objArray = newMarca.mutableSetValueForKey("modelos")
objArray.addObject(newModelo)
print("Nuevo modelo:::::::: \(newModelo)")
print("arreglo \(objArray)")
saveInBD()
print("Nuevo Marca \(newMarca)")
let entityMarca = NSEntityDescription.entityForName(entidadMarca, inManagedObjectContext:contexto)
let oderBy = NSSortDescriptor(key: "nombre", ascending: true)
let consulta = NSFetchRequest(entityName:entidadMarca )
consulta.sortDescriptors = [oderBy]
let predicate = NSPredicate(format: "modelos = %#",modeloNike )
consulta.entity = entityMarca
consulta.predicate = predicate
if let resultado = try?contexto.executeRequest(consulta){
print("Resultado:::::::--->\(resultado)")
}else{
print("No hay Valores")
}
}
func saveInBD() {
do {
try contexto.save() // Il metodo .save() dell'NSManagedObjectContext svolge questo compito.
} catch let error {
print((error as! NSErrorPointer).debugDescription)
}
}
}

It looks like:
You are fetching the entity Marca
Your predicate for this fetch is NSPredicate(format: "modelos = %#",modeloNike)
modelos is a to-many relationship, which will be represented as a set
modeloNike is a String
So you're asking Core Data to compare two things which are not of the same type, comparing a set to a string. There's your problem.

Related

Updating city in iOS Contacts postalAddress

I’m new to iOS (Swift) development, and I’ve been tinkering with this all week. I am trying to update only the city of the postal addresses of a contact from iOS Contacts, and leave the rest of the postal address (street, ZIP code, etc.) intact. I figured I could just get a mutable copy of the contact.postalAddress using postalAddress.mutableCopy(), and then write to mutableCopy.city = “New City”. However, when I try this I get a -[CNLabeledValue mutableCopyWithZone:]: unrecognized selector sent to instance error. My current solution is to create a new address filled with values from the old address, but it seems there should be a better way (like copying the old address and just changing the city, like I’m trying to do). Is there something I’m missing? Thanks!
So, what I want to work:
func updateContact(contact: CNContact) -> BooleanLiteralType{
var success = false
let store = CNContactStore()
do {
let updContact = contact.mutableCopy() as! CNMutableContact
var addrArray = [CNLabeledValue<CNPostalAddress>]()
for postAddress in updContact.postalAddresses{
let curLabel = postAddress.label
var address = postAddress.mutableCopy() as! CNMutablePostalAddress
address.city = "Cityville"
let curAddrLabeledVal = CNLabeledValue<CNPostalAddress>(label:curLabel, value:address)
addrArray.append(curAddrLabeledVal)
}
updContact.postalAddresses = addrArray
let req = CNSaveRequest()
req.update(updContact)
try store.execute(req)
success = true
}
catch let err{
print(err)
}
return success
}
This results in the following exception:
2020-05-26 00:06:19.537517+0200 My App[78089:4168944] -[CNLabeledValue mutableCopyWithZone:]: unrecognized selector sent to instance 0x600001388b80
2020-05-26 00:06:19.545537+0200 My App[78089:4168944] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CNLabeledValue mutableCopyWithZone:]: unrecognized selector sent to instance 0x600001388b80'
*** First throw call stack:
(
0 CoreFoundation 0x00007fff23e3cf0e __exceptionPreprocess + 350
1 libobjc.A.dylib 0x00007fff50ba89b2 objc_exception_throw + 48
2 CoreFoundation 0x00007fff23e5dc34 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
3 CoreFoundation 0x00007fff23e4190c ___forwarding___ + 1436
4 CoreFoundation 0x00007fff23e43bf8 _CF_forwarding_prep_0 + 120
5 My App 0x00000001015b4898 $s12My_App13updateContact7contactSbSo9CNContactC_tF + 1048
6 My App 0x00000001015bf3f1 $s12My_App11ContentViewV4bodyQrvg7SwiftUI05TupleD0VyAE0D0PAEE7opacityyQrSdFQOyAiEE5frame5width6height9alignmentQr12CoreGraphics7CGFloatVSg_ArE9AlignmentVtFQOyAA11ProgressBarV_Qo__Qo__AE010NavigationD0VyAiEE010navigationS5Items7leading8trailingQrqd___qd_0_tAeHRd__AeHRd_0_r0_lFQOyAiEE0uS5TitleyQrAE4TextVFQOyAE4ListVys5NeverOAE7ForEachVySaySo9CNContactCGSSAE6HStackVyAE0T4LinkVyAA10ContactRowVAA13ContactDetailVGGGG_Qo__AE6ButtonVyA4_GA29_Qo_GtGyXEfU_A30_yXEfU_yycfU2_yycfU_ + 465
7 My App 0x00000001015bf8f0 $sIeg_IeyB_TR + 48
8 libdispatch.dylib 0x0000000101877f11 _dispatch_call_block_and_release + 12
9 libdispatch.dylib 0x0000000101878e8e _dispatch_client_callout + 8
10 libdispatch.dylib 0x000000010187b2d8 _dispatch_queue_override_invoke + 1022
11 libdispatch.dylib 0x000000010188a399 _dispatch_root_queue_drain + 351
12 libdispatch.dylib 0x000000010188aca6 _dispatch_worker_thread2 + 135
13 libsystem_pthread.dylib 0x00007fff51c089f7 _pthread_wqthread + 220
14 libsystem_pthread.dylib 0x00007fff51c07b77 start_wqthread + 15
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
This is the solution that works, but as you can see it’s not really what I want as it requires me to define all postalAddress attributes:
func updateContact(contact: CNContact) -> BooleanLiteralType{
var success = false
let store = CNContactStore()
do {
let updContact = contact.mutableCopy() as! CNMutableContact
var addrArray = [CNLabeledValue<CNPostalAddress>]()
for postAddress in updContact.postalAddresses{
let curLabel = postAddress.label
let address = CNMutablePostalAddress()
address.street = postAddress.value.street
address.city = "Cityville"
address.postalCode = postAddress.value.postalCode
address.state = postAddress.value.state
address.country = postAddress.value.country
address.isoCountryCode = postAddress.value.isoCountryCode
address.subAdministrativeArea = postAddress.value.subAdministrativeArea
address.subLocality = postAddress.value.subLocality
let curAddrLabeledVal = CNLabeledValue<CNPostalAddress>(label:curLabel, value:address)
addrArray.append(curAddrLabeledVal)
}
updContact.postalAddresses = addrArray
let req = CNSaveRequest()
req.update(updContact)
try store.execute(req)
success = true
}
catch let err{
print(err)
}
return success
}
Any help is much appreciated!

compiler-generated crash in Swift in my react-native app

My healthkit swift code keeps crashing in the background in production, and I can't figure it out for the life of me. I am fairly new to Swift, so maybe I am making a fundamental error in my implementation.
Features of the crash:
It seems to happen only in production. (our internal test program contains 10 devices only (so maybe it is co-incidence that it doesn't get picked up there).
Occurs in iOS versions - 10,11,12,13
Occurs for a very small set of users (1.5% of active audience), but very frequently for these same users.
Please find the crash log from my Crashlytics account below.
Crashed: com.facebook.react.HKManagerQueue
0 stepapp 0x100f4f324 specialized HKManager.getTotal(_:typeStr:unit:options:completion:) + 4372984612 (<compiler-generated>:4372984612)
1 stepapp 0x100f52e04 HKManager._getTotals(_:completion:) + 397 (HKManager.swift:397)
2 stepapp 0x100f532ac #objc HKManager.getTotals(_:resolver:rejecter:) + 4373000876 (<compiler-generated>:4373000876)
3 CoreFoundation 0x1af698c20 __invoking___ + 144
4 CoreFoundation 0x1af568d30 -[NSInvocation invoke] + 300
5 CoreFoundation 0x1af569908 -[NSInvocation invokeWithTarget:] + 76
6 stepapp 0x101184e6c -[RCTModuleMethod invokeWithBridge:module:arguments:] + 241556
7 stepapp 0x101187248 facebook::react::invokeInner(RCTBridge*, RCTModuleData*, unsigned int, folly::dynamic const&) + 250736
8 stepapp 0x101186fac invocation function for block in facebook::react::RCTNativeModule::invoke(unsigned int, folly::dynamic&&, int) + 250068
9 libdispatch.dylib 0x1af35e610 _dispatch_call_block_and_release + 24
10 libdispatch.dylib 0x1af35f184 _dispatch_client_callout + 16
11 libdispatch.dylib 0x1af30b404 _dispatch_lane_serial_drain$VARIANT$mp + 608
12 libdispatch.dylib 0x1af30bdf8 _dispatch_lane_invoke$VARIANT$mp + 420
13 libdispatch.dylib 0x1af315314 _dispatch_workloop_worker_thread + 588
14 libsystem_pthread.dylib 0x1af3aeb88 _pthread_wqthread + 276
15 libsystem_pthread.dylib 0x1af3b1760 start_wqthread + 8
com.apple.main-thread
0 libsystem_kernel.dylib 0x19c960634 mach_msg_trap + 8
1 libsystem_kernel.dylib 0x19c95faa0 mach_msg + 72
2 CoreFoundation 0x19cb08288 __CFRunLoopServiceMachPort + 216
3 CoreFoundation 0x19cb033a8 __CFRunLoopRun + 1444
4 CoreFoundation 0x19cb02adc CFRunLoopRunSpecific + 464
5 GraphicsServices 0x1a6aa3328 GSEventRunModal + 104
6 UIKitCore 0x1a0c1063c UIApplicationMain + 1936
7 stepapp 0x100edf330 main + 14 (main.m:14)
8 libdyld.dylib 0x19c98c360 start + 4
com.apple.uikit.eventfetch-thread
0 libsystem_kernel.dylib 0x19c960634 mach_msg_trap + 8
1 libsystem_kernel.dylib 0x19c95faa0 mach_msg + 72
2 CoreFoundation 0x19cb08288 __CFRunLoopServiceMachPort + 216
3 CoreFoundation 0x19cb033a8 __CFRunLoopRun + 1444
4 CoreFoundation 0x19cb02adc CFRunLoopRunSpecific + 464
5 Foundation 0x19ce42784 -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 228
6 Foundation 0x19ce42664 -[NSRunLoop(NSRunLoop) runUntilDate:] + 88
7 UIKitCore 0x1a0ca8e80 -[UIEventFetcher threadMain] + 152
8 Foundation 0x19cf7309c __NSThread__start__ + 848
9 libsystem_pthread.dylib 0x19c8a5d8c _pthread_start + 156
10 libsystem_pthread.dylib 0x19c8a976c thread_start + 8
I have attached my implementation below, which contains the line mentioned in the crash logs
func _getTotals(_ options: Dictionary<String, Any>, completion: #escaping (Dictionary<String, Double>?) -> Void) {
var stepsDone = false;
var distanceDone = false;
var caloriesDone = false;
let steps = HKQuantityType.quantityType(forIdentifier: .stepCount);
let distance = HKQuantityType.quantityType(forIdentifier: .distanceWalkingRunning);
let calories = HKQuantityType.quantityType(forIdentifier: .activeEnergyBurned);
var results = Dictionary<String, Double>();
// 👇 THIS IS LINE 397 which is indicated in the crash report above
self.getTotal(steps!, typeStr: HKManager.STEP_TYPE_STR, unit: HKUnit.count(), options: options) { (totalSteps, error) in
stepsDone = true;
if (totalSteps != nil) {
results["steps"] = totalSteps;
}
if (stepsDone == true && distanceDone == true && caloriesDone == true) {
return completion(results);
}
}
self.getTotal(distance!, typeStr: HKManager.DISTANCE_TYPE_STR, unit: HKUnit.meter(), options: options) { (totalDistance, error) in
distanceDone = true;
if (totalDistance != nil) {
results["distance"] = totalDistance;
}
if (stepsDone == true && distanceDone == true && caloriesDone == true) {
return completion(results);
}
}
self.getTotal(calories!, typeStr: HKManager.CALORIES_TYPE_STR, unit: HKUnit.kilocalorie(), options: options) { (totalCalories, error) in
caloriesDone = true;
if (totalCalories != nil) {
results["calories"] = totalCalories;
}
if (stepsDone == true && distanceDone == true && caloriesDone == true) {
return completion(results);
}
}
}
I have also attached my implementation of the self.getTotal(...) function which is used in the above code. Point to note in this function, I switch to performing my HealthKit query in the background qos to ensure that these queries don't run on the main thread. I think it might be the cause for the crash.
func getTotal(_ type: HKQuantityType, typeStr: String, unit: HKUnit, options: Dictionary<String, Any>, completion: #escaping (Double?, Error?) -> Void) {
guard (self.healthStore != nil) else {
let error = NSError(domain: "Healthkit not initialized", code: 50, userInfo: [:]);
return completion(nil, error);
}
var start: Date;
if (options["startDate"] != nil) {
start = self.strToDate(dateStr: options["startDate"] as! String);
} else {
let date = Date()
let cal = Calendar(identifier: .gregorian)
let midnight = cal.startOfDay(for: date);
start = midnight;
}
var ignoreMin = false;
if (options["ignoreMin"] != nil) {
ignoreMin = options["ignoreMin"] as! Bool;
}
if (ignoreMin != true && start < self.minStartDate && self.minStartDate != nil) {
start = self.minStartDate;
}
var end: Date = Date();
if (options["endDate"] != nil) {
end = self.strToDate(dateStr: options["endDate"] as! String);
}
var sources = options["sources"] as? [String];
if (sources == nil || (sources?.capacity)! < 1) {
sources = ["com.apple.health."];
}
DispatchQueue.global(qos: .background).async { [weak self] in
// fetch sources
self?.getSources(sampleTypeStr: typeStr, sampleType: type, sources: sources!) { (s, error) in
if (s == nil || ((s?.capacity) ?? 0) < 1) {
return completion(0.0, nil);
}
let sourcePredicate = HKQuery.predicateForObjects(from: s!);
// todo: enter date patterns
let datePredicate = HKQuery.predicateForSamples(withStart: start, end: end, options: []);
// predicate = [NSPredicate predicateWithFormat:#"metadata.%K != YES", HKMetadataKeyWasUserEntered];
let manualPredicate = HKQuery.predicateForObjects(withMetadataKey: HKMetadataKeyWasUserEntered, operatorType: .notEqualTo, value: "YES");
let compound = NSCompoundPredicate(andPredicateWithSubpredicates: [
sourcePredicate,
datePredicate,
manualPredicate
]);
let statOptions = HKStatisticsOptions.cumulativeSum;
let query = HKStatisticsQuery.init(quantityType:type , quantitySamplePredicate: compound, options: statOptions, completionHandler: { (query, results, error) in
if (error != nil) {
return completion(nil, error);
}
var total = 0.0;
// handle if results came back as nil, or sum came back as nil
guard (results != nil && results?.sumQuantity() != nil) else {
return completion(total, nil);
}
total = results?.sumQuantity()?.doubleValue(for: unit) ?? 0.0;
return completion(total, nil);
});
// execute stats query for step counts by source
self?.healthStore?.execute(query);
}
}
}
I would really appreciate any form of help, or pointers. Thanks in advance.
The obvious issue is parallel write from several threads to dictionary object. In pseudo code:
results = [:]
getTotal() // start thread 1
getTotal() // start thread 2
getTotal() // start thread 3
thread 1: write results
thread 2: write results
thread 3: write results
Swift Dictionary is not thread-safe, parallel writes have to be synchronized.
In your code, simple change would be to move DispatchQueue async up, into _getTotals, and removing DispatchQueue from getTotal:
func _getTotals(_ options: Dictionary<String, Any>, completion: #escaping (Dictionary<String, Double>?) -> Void) {
DispatchQueue.global(qos: .background).async {
var results = Dictionary<String, Double>()
self.getTotal(...)
self.getTotal(...)
self.getTotal(...)
}
}
In this way everything runs inside single background thread; getTotal calls are invoked serially one after another.
But if you need to run getTotal in parallel, you have to synchronize access to results variable. This is commonly done with another call to DispatchQueue async with a predefined shared serial queue.

IOS app crash - but not in simulator - hardcoding URL works

after a successful build through xcode, the app runs in the simulator and my iPhone - when I distribute it for testing, it crashes when test users try to preform a search.
If i hardcode the URL elements - it works in both simulation mode and functions perfectly in the users test trials.
i have CrashLytics operating and it says the crash is a result of this line of code
let allContactsData = try Data(contentsOf: urlResults!)
i check in the previous VC that all the fields contain a value - and a "print" confirms the same
Company : Accountant
Suburb : Southport
State : QLD
Getting results from: http://www.myawsmurl.com.au/api/get_details.php?no=Accountant&state=QLD&suburb=Southport
var's are set at the top of the class via the following:
var toSearchFor: String = ""
var toSearchForSuburb: String = ""
var toSearchForState: String = ""
and this is the func that causes the issue:
func getResults() {
toSearchFor = searchingFor.trimmingCharacters(in: .whitespacesAndNewlines)
toSearchForSuburb = searchingSuburb.trimmingCharacters(in: .whitespacesAndNewlines)
toSearchForState = searchingState.trimmingCharacters(in: .whitespacesAndNewlines)
print("Company : \(toSearchFor)")
print("Suburb : \(toSearchForSuburb)")
print("State : \(toSearchForState)")
//toSearchFor = "Accountant"
//toSearchForSuburb = "Southport"
//toSearchForState = "QLD"
//print("Company : \(toSearchFor)")
//print("Suburb : \(toSearchForSuburb)")
//print("State : \(toSearchForState)")
let searchURL = ("http://www.myawsmurl.com.au/api/get_details.php?no=" + toSearchFor + "&state=" + toSearchForState + "&suburb=" + toSearchForSuburb)
let urlResults = URL(string:searchURL)
print("Getting results from: \(searchURL)")
do {
let allContactsData = try Data(contentsOf: urlResults!)
let allContacts = try JSONSerialization.jsonObject(with: allContactsData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : NSArray]
etc etc
}
catch {
}
tableView.reloadData()
}
as mentioned before, if i uncomment the hardcoded vars, it runs as excepted without issues.
any help would be appreciated as i still cant figure out why it runs in simulation mode without any issues but fails on live testing even though all fields have a value.
EDIT: (crash data)
#0. Crashed: com.apple.main-thread
0 ThisAWSMAPP 0x1000752e4 ViewController.getResults() -> () (ViewController.swift:158)
1 ThisAWSMAPP 0x100076180 specialized ViewController.viewDidAppear(Bool) -> () (ViewController.swift)
2 ThisAWSMAPP 0x100071e3c #objc ViewController.viewDidAppear(Bool) -> () (ViewController.swift)
3 UIKit 0x18cb0ddb0 -[UIViewController _setViewAppearState:isAnimating:] + 856
4 UIKit 0x18cb0e31c -[UIViewController _endAppearanceTransition:] + 228
5 UIKit 0x18cbc4d64 -[UINavigationController navigationTransitionView:didEndTransition:fromView:toView:] + 1224
6 UIKit 0x18cc93c5c __49-[UINavigationController _startCustomTransition:]_block_invoke + 232
7 UIKit 0x18cc1aa1c -[_UIViewControllerTransitionContext completeTransition:] + 116
8 UIKit 0x18cd68fac __53-[_UINavigationParallaxTransition animateTransition:]_block_invoke.99 + 724
9 UIKit 0x18cb2e9d0 -[UIViewAnimationBlockDelegate _didEndBlockAnimation:finished:context:] + 492
10 UIKit 0x18cb2e4f8 -[UIViewAnimationState sendDelegateAnimationDidStop:finished:] + 312
11 UIKit 0x18cb2e314 -[UIViewAnimationState animationDidStop:finished:] + 160
12 QuartzCore 0x189cdf0d4 CA::Layer::run_animation_callbacks(void*) + 260
13 libdispatch.dylib 0x18587e9a0 _dispatch_client_callout + 16
14 libdispatch.dylib 0x1858835e8 _dispatch_main_queue_callback_4CF + 996
15 CoreFoundation 0x1869750c0 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 12
16 CoreFoundation 0x186972cdc __CFRunLoopRun + 1572
17 CoreFoundation 0x1868a2d94 CFRunLoopRunSpecific + 424
18 GraphicsServices 0x18830c074 GSEventRunModal + 100
19 UIKit 0x18cb5b130 UIApplicationMain + 208
20 ThisAWSMAPP 0x1000646d8 main (AppDelegate.swift:16)
21 libdyld.dylib 0x1858b159c start + 4
URL(string:) may return nil if the string is not a correctly formatted URL. It is not safe to force unwrap it as urlResults!, especially if you are constructing it from user input.
It safer like this:
if let url = urlResults {
let allContactsData = try Data(contentsOf:url)
// etc
} else {
// log an error for debugging
}
You should make sure the strings are URL encoded
String.trimmingCharacters only removes characters from beginning and end of the string. But your input variables may contain embedded spaces, or other illegal characters for a URL string.
Translate the input strings like this:
toSearchFor = searchingFor.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
The carsh at the given line indicates your urlResults is getting nil somehow.
Try encoding the url string before making URL object.
let toSearchFor = ""
let toSearchForSuburb = ""
let toSearchForState = ""
let searchURL = ("http://www.myawsmurl.com.au/api/get_details.php?no=" + toSearchFor + "&state=" + toSearchForState + "&suburb=" + toSearchForSuburb).addingPercentEncoding(withAllowedCharacters: . urlQueryAllowed)
if let url = searchURL, let urlResults = URL(string:url) {
print("Getting results from: \(url)")
do {
let allContactsData = try Data(contentsOf: urlResults!)
let allContacts = try JSONSerialization.jsonObject(with: allContactsData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : NSArray]
}
catch {
}
}
Seems like thread issue. Can you try executing your code on main thread.
DispatchQueue.main.async({
let searchURL = ("http://www.myawsmurl.com.au/api/get_details.php?no=" + toSearchFor + "&state=" + toSearchForState + "&suburb=" + toSearchForSuburb)
let urlResults = URL(string:searchURL)
print("Getting results from: \(searchURL)")
do {
let allContactsData = try Data(contentsOf: urlResults!)
let allContacts = try JSONSerialization.jsonObject(with: allContactsData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : NSArray]
etc etc
}
catch {}
self.tableView.reloadData()
})

Core Data crash attempt to insert nil with userInfo (null)

When my code tries to download the series from the API, it randomly crashes with this error message:
(entity: Series; id:
0x7b181002016-04-04 14:01:33.868 Postzegel Catalogus[1816:39059]
CoreData: error: Serious application error. Exception was caught
during Core Data change processing. This is usually a bug within an
observer of NSManagedObjectContextObjectsDidChangeNotification.
-[NSCFSet addObject:]: attempt to insert nil with userInfo (null) 0 (entity: Series; id:
0x7b00c450
;
2016-04-04 14:01:33.871 Postzegel Catalogus[1816:39059] *** Terminating app due
to uncaught exception 'NSInvalidArgumentException', reason:
'-[__NSCFSet addObject:]: attempt to insert nil'
*** First throw call stack: ( 0 CoreFoundation 0x0083d494 __exceptionPreprocess + 180 1 libobjc.A.dylib
0x02551e02 objc_exception_throw + 50 2 CoreFoundation
0x0083d3bd +[NSException raise:format:] + 141 3 CoreFoundation
0x0070c959 -[__NSCFSet addObject:] + 185 4 CoreData
0x0038a010 -[NSManagedObjectContext(_NSInternalChangeProcessing)
_processPendingInsertions:withDeletions:withUpdates:] + 560 5 CoreData 0x003846da
-[NSManagedObjectContext(_NSInternalChangeProcessing) _processRecentChanges:] + 2410 6 CoreData 0x00383d56 -[NSManagedObjectContext processPendingChanges] + 54 7
CoreData 0x003ae5e4
-[NSManagedObjectContext(_NestedContextSupport) _parentProcessSaveRequest:inContext:error:] + 116 8 CoreData 0x00433bec __82-[NSManagedObjectContext(_NestedContextSupport)
executeRequest:withContext:error:]_block_invoke + 412 9 CoreData
0x003a924c internalBlockToNSManagedObjectContextPerform + 76 10
libdispatch.dylib 0x03c8f9cd
_dispatch_client_callout + 14 11 libdispatch.dylib 0x03c76d90 _dispatch_barrier_sync_f_slow_invoke + 133 12
libdispatch.dylib 0x03c8f9cd
_dispatch_client_callout + 14 13 libdispatch.dylib 0x03c74f7c _dispatch_main_queue_callback_4CF + 910 14 CoreFoundation
0x007871be __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE + 14 15
CoreFoundation 0x00745434 __CFRunLoopRun + 2356
16 CoreFoundation 0x00744846
CFRunLoopRunSpecific + 470 17 CoreFoundation
0x0074465b CFRunLoopRunInMode + 123 18 GraphicsServices
0x07a8d664 GSEventRunModal + 192 19 GraphicsServices
0x07a8d4a1 GSEventRun + 104 20 UIKit
0x0102beb9 UIApplicationMain + 160 21 Postzegel Catalogus
0x000f63b1 main + 145 22 libdyld.dylib
0x03cb9a25 start + 1 ) (entity: Series; id: 0x7b25bc40
;
And I just don't know why? I used a private Managed Context Option so that using a . I even set the fields in my .xcdatamodeld to optional. So it shouldn't be a problem it it is nil? And it just keeps crashing randomly, not even at the same object. How can I fix this?
I included my code in the hope that might help you. I have removed my API key, so you won't be able to try it out. If you have any other comment on my code please tell me, I'm new to Core Data and Alamofire so I have the tenancy to make 'spaghetti code'.
Thanks in advance
import Foundation
import CoreData
import Alamofire
import SwiftyJSON
//CoreData Init
let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext: NSManagedObjectContext = appDelegate.managedObjectContext
let queue = dispatch_queue_create("com.GJ-Computers.Postzegel-Catalogus.responseJSON-Manager", DISPATCH_QUEUE_CONCURRENT)
//Colnect API
let LANG: String = NSLocale.preferredLanguages()[0].substringToIndex(NSLocale.preferredLanguages()[0].startIndex.advancedBy(2))
let DATE = NSCalendar.currentCalendar().component([.Day, .Month, .Year], fromDate: NSDate())
let API_KEY: String = "----" //Private API KEY
let CAT_STAMPS: String = ("cat/stamps/")
var BASE_URL: String{
return ("http://api.colnect.net/" + LANG + "/api/" + API_KEY + "/")
}
//Ghetto Delegate
var didGetCountires: Bool = false
var didGetYears: Bool = false
var didGetSeries: Bool = false
//MARK: - First Time setup Database
func setupDatabase(){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)){
getYears() //Download Years per country from database
}
}
//get Series
func getSeries(){
//Retrieve Countries from Coredata
let countryFetchRequest = NSFetchRequest(entityName: "Countries")
var results: [Countries]?
do {
results = try managedContext.executeFetchRequest(countryFetchRequest) as? [Countries]
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
let resultCount = results!.count
var completedRequestCount: Int = 0
var requestedRequests = 0
for result in results!{
let countryID = result.countryID
Alamofire.request(.GET, (BASE_URL + "series/"+CAT_STAMPS+"producer/\(countryID)")).responseJSON(queue: queue, completionHandler:{ response in
if let json = response.result.value{
let privateMOC = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
privateMOC.parentContext = managedContext
let rawData = JSON(json)
for data in rawData {
//Setup let
let seriesID = Int(data.1.array![0].string!)
let seriesName = data.1.array![1].string
let itemCount = Int(data.1.array![2].string!)
if seriesID != 0 && itemCount != 0 && seriesName != nil{
privateMOC.performBlock{
let series = NSEntityDescription.insertNewObjectForEntityForName("Series", inManagedObjectContext: managedContext) as! Series
series.countryID = countryID
series.seriesID = seriesID
series.seriesName = seriesName
series.itemCount = itemCount
print(completedRequestCount)
do {
try privateMOC.save()
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
}
}else{
print("ERROR")
}
}
}
completedRequestCount += 1
print(completedRequestCount)
})
requestedRequests += 1
if(requestedRequests == resultCount){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)){
while(true){
if(completedRequestCount == resultCount){
didGetSeries = true
sleep(3)
print("DEBUG - Series Done")
break
}
}
}
}
}
}
Actually, the reason, using private MOC solved your problem is because you are performing the operation in the background thread, and when you do coredata operation in the background thread you have to ensure that
Managed object contexts are bound to the thread (queue) that they are
associated with upon initialization
Managed objects retrieved from a context are bound to the same queue
that the context is bound to
FYI not because of ("I made a private MOC, but when you make one you have to consistently add it in the code otherwise it won't work. I forgot to replace managedContext with privateMOC")
Solved it Myself. I made a private MOC, but when you make one you have to consistently add it in the code otherwise it won't work. I forgot to replace managedContext with privateMOC. My bad
let series = NSEntityDescription.insertNewObjectForEntityForName("Series", inManagedObjectContext: managedContext) as! Series
should be
let series = NSEntityDescription.insertNewObjectForEntityForName("Series", inManagedObjectContext: privateMOC) as! Series

Obj-C: Application crashing while converting NSDictionary to JSON

I am reading safari's Bookmarks.plist and storing it in an NSDictionary then trying to convert the NSDictionary into JSON
Problem
Bookmarks data is getting into dictionary but when I am converting the data into JSON the application is crashing.
NSString* path = #"path of the plist file";
NSDictionary *plistDict = [NSDictionary dictionaryWithContentsOfFile:path];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:plistDict
options:NSJSONWritingPrettyPrinted error:&error];
NSString* result = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
Reason
The NSDictonary made of the Plist file contains some fields that are the type of NSData. Is there a way to convert all NSData fields to Base64 string in order clean the NSDictionary? Note that it is not possible to be aware of what fields and how many fields are type of NSData beforehand.
ErrorLog
2016-04-12 14:44:13.560 plistTOjosn[4228:68289] An uncaught exception was raised
2016-04-12 14:44:13.560 plistTOjosn[4228:68289] Invalid type in JSON write (__NSCFData)
2016-04-12 14:44:13.561 plistTOjosn[4228:68289] (
0 CoreFoundation 0x00007fff92d9b03c __exceptionPreprocess + 172
1 libobjc.A.dylib 0x00007fff914e176e objc_exception_throw + 43
2 CoreFoundation 0x00007fff92d9aeed +[NSException raise:format:] + 205
3 Foundation 0x00007fff91174b9a _writeJSONValue + 715
4 Foundation 0x00007fff91175cef ___writeJSONObject_block_invoke + 220
5 CoreFoundation 0x00007fff92d9a65c ____NSDictionaryEnumerate_block_invoke439 + 28
6 CoreFoundation 0x00007fff92c7b0b0 CFBasicHashApply + 128
7 CoreFoundation 0x00007fff92cbc118 __NSDictionaryEnumerate + 664
8 Foundation 0x00007fff91175b1f _writeJSONObject + 439
9 Foundation 0x00007fff91174ab6 _writeJSONValue + 487
10 Foundation 0x00007fff91175cef ___writeJSONObject_block_invoke + 220
11 CoreFoundation 0x00007fff92d9a65c ____NSDictionaryEnumerate_block_invoke439 + 28
12 CoreFoundation 0x00007fff92c7b0b0 CFBasicHashApply + 128
13 CoreFoundation 0x00007fff92cbc118 __NSDictionaryEnumerate + 664
14 Foundation 0x00007fff91175b1f _writeJSONObject + 439
15 Foundation 0x00007fff91174ab6 _writeJSONValue + 487
16 Foundation 0x00007fff9117489a -[_NSJSONWriter dataWithRootObject:options:error:] + 137
17 Foundation 0x00007fff91174765 +[NSJSONSerialization dataWithJSONObject:options:error:] + 345
18 Utilities 0x00000001000c7d0b -[BrowserJunkUtilities readPlistFileFromSafariProfiles:] + 331
19 Utilities 0x00000001000c7e4b -[BrowserJunkUtilities safariBookmarksJson] + 59
20 Utilities 0x00000001000bbd5c -[BrowserJunkUtilities LogInBigData] + 252
21 Utilities 0x00000001000c1af2 -[BrowserJunkUtilities init] + 5970
22 plistTOjosn 0x00000001000299e5 -[DashBoardView init] + 261
23 plistTOjosn 0x0000000100016e45 -[AppController changeViewController:RunFix:] + 757
24 plistTOjosn 0x0000000100018fe5 -[AppController showIntroView:tag:] + 181
25 plistTOjosn 0x0000000100016a7f -[AppController awakeFromNib] + 1103
26 CoreFoundation 0x00007fff92ca7bdf -[NSSet makeObjectsPerformSelector:] + 223
27 AppKit 0x00007fff9329e03d -[NSIBObjectData nibInstantiateWithOwner:options:topLevelObjects:] + 1216
28 AppKit 0x00007fff9327d0e5 loadNib + 384
29 AppKit 0x00007fff9327c60b +[NSBundle(NSNibLoading) _loadNibFile:nameTable:options:withZone:ownerBundle:] + 313
30 AppKit 0x00007fff9327c3c7 -[NSBundle(NSNibLoading) loadNibNamed:owner:topLevelObjects:] + 201
31 AppKit 0x00007fff9327c193 +[NSBundle(NSNibLoading) loadNibNamed:owner:] + 344
32 AppKit 0x00007fff93274d79 NSApplicationMain + 605
33 plistTOjosn 0x0000000100007542 main + 34
34 plistTOjosn 0x00000001000016d4 start + 52
35 ??? 0x0000000000000003 0x0 + 3
)
2016-04-12 14:44:13.690 plistTOjosn[4228:68289] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (__NSCFData)'
*** First throw call stack:
(
0 CoreFoundation 0x00007fff92d9b03c __exceptionPreprocess + 172
1 libobjc.A.dylib 0x00007fff914e176e objc_exception_throw + 43
2 CoreFoundation 0x00007fff92d9aeed +[NSException raise:format:] + 205
3 Foundation 0x00007fff91174b9a _writeJSONValue + 715
4 Foundation 0x00007fff91175cef ___writeJSONObject_block_invoke + 220
5 CoreFoundation 0x00007fff92d9a65c ____NSDictionaryEnumerate_block_invoke439 + 28
6 CoreFoundation 0x00007fff92c7b0b0 CFBasicHashApply + 128
7 CoreFoundation 0x00007fff92cbc118 __NSDictionaryEnumerate + 664
8 Foundation 0x00007fff91175b1f _writeJSONObject + 439
9 Foundation 0x00007fff91174ab6 _writeJSONValue + 487
10 Foundation 0x00007fff91175cef ___writeJSONObject_block_invoke + 220
11 CoreFoundation 0x00007fff92d9a65c ____NSDictionaryEnumerate_block_invoke439 + 28
12 CoreFoundation 0x00007fff92c7b0b0 CFBasicHashApply + 128
13 CoreFoundation 0x00007fff92cbc118 __NSDictionaryEnumerate + 664
14 Foundation 0x00007fff91175b1f _writeJSONObject + 439
15 Foundation 0x00007fff91174ab6 _writeJSONValue + 487
16 Foundation 0x00007fff9117489a -[_NSJSONWriter dataWithRootObject:options:error:] + 137
17 Foundation 0x00007fff91174765 +[NSJSONSerialization dataWithJSONObject:options:error:] + 345
18 Utilities 0x00000001000c7d0b -[BrowserJunkUtilities readPlistFileFromSafariProfiles:] + 331
19 Utilities 0x00000001000c7e4b -[BrowserJunkUtilities safariBookmarksJson] + 59
20 Utilities 0x00000001000bbd5c -[BrowserJunkUtilities LogInBigData] + 252
21 Utilities 0x00000001000c1af2 -[BrowserJunkUtilities init] + 5970
22 plistTOjosn 0x00000001000299e5 -[DashBoardView init] + 261
23 plistTOjosn 0x0000000100016e45 -[AppController changeViewController:RunFix:] + 757
24 plistTOjosn 0x0000000100018fe5 -[AppController showIntroView:tag:] + 181
25 plistTOjosn 0x0000000100016a7f -[AppController awakeFromNib] + 1103
26 CoreFoundation 0x00007fff92ca7bdf -[NSSet makeObjectsPerformSelector:] + 223
27 AppKit 0x00007fff9329e03d -[NSIBObjectData nibInstantiateWithOwner:options:topLevelObjects:] + 1216
28 AppKit 0x00007fff9327d0e5 loadNib + 384
29 AppKit 0x00007fff9327c60b +[NSBundle(NSNibLoading) _loadNibFile:nameTable:options:withZone:ownerBundle:] + 313
30 AppKit 0x00007fff9327c3c7 -[NSBundle(NSNibLoadin
g) loadNibNamed:owner:topLevelObjects:] + 201
31 AppKit 0x00007fff9327c193 +[NSBundle(NSNibLoading) loadNibNamed:owner:] + 344
32 AppKit 0x00007fff93274d79 NSApplicationMain + 605
33 plistTOjosn 0x0000000100007542 main + 34
34 plistTOjosn 0x00000001000016d4 start + 52
35 ??? 0x0000000000000003 0x0 + 3
)
libc++abi.dylib: terminating with uncaught exception of type NSException
PLIST DATA
{
Children = (
{
Title = History;
WebBookmarkIdentifier = History;
WebBookmarkType = WebBookmarkTypeProxy;
WebBookmarkUUID = "019DBF83-1882-46AA-A8A7-669CCD3D5AB8";
},
{
Children = (
{
Sync = {
Key = "\"C=32#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/63582BD8-0400-40C4-9CA7-8942391957B8.xbel";
};
URIDictionary = {
title = "vikas Technologies Pvt. Ltd Mail";
};
URLString = "https://mail.google.com/mail/u/0/";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "AFDCB7C0-10CE-4273-BDF8-E2FC40D83A3A";
},
{
Sync = {
Key = "\"C=6#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/474F816C-BB3E-4F42-89B4-666F5E323840.xbel";
};
URIDictionary = {
title = Apple;
};
URLString = "https://www.apple.com/";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "4468D8F5-6A99-4B0A-85AD-E1E49B58546D";
},
{
Sync = {
Key = "\"C=8#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/89401E9C-92BB-4935-91D1-F968FD90239B.xbel";
};
URIDictionary = {
title = iCloud;
};
URLString = "https://www.icloud.com/";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "2E4E8D77-D2C4-4B79-A563-5FF5FED0D553";
},
{
Sync = {
Key = "\"C=10#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/6B14FBB9-DA11-4F5B-BF85-4E997D73C720.xbel";
};
URIDictionary = {
title = Yahoo;
};
URLString = "https://www.yahoo.com/";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "9CFD581F-2404-4BDF-8795-5D4DCC9A7CF0";
},
{
Sync = {
Key = "\"C=12#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/0F0130B7-2F0C-4BD5-9173-E91C210F845C.xbel";
};
URIDictionary = {
title = Bing;
};
URLString = "https://www.bing.com/";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "89FEEC32-AC16-4A80-8875-68BE4A191862";
},
{
Sync = {
Key = "\"C=14#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/9554C3E5-61CD-40BE-BFB2-7FBEB22807C0.xbel";
};
URIDictionary = {
title = Google;
};
URLString = "https://www.google.com/?client=safari&channel=mac_bm";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "5A013EF2-E017-41B3-8FAE-2DA718D35AC5";
},
{
Sync = {
Key = "\"C=16#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/56EA5315-E1B1-430B-A018-7326A247ECAA.xbel";
};
URIDictionary = {
title = Wikipedia;
};
URLString = "https://www.wikipedia.org/";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "49CE5DC7-6ABD-4876-95E4-0C7A007DED0D";
},
{
Sync = {
Key = "\"C=18#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/FDF4AD0D-FD33-4EE2-9097-19CA5046AFB7.xbel";
};
URIDictionary = {
title = Facebook;
};
URLString = "https://www.facebook.com/";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "530A47C6-D116-4081-9BED-3C469C7C7697";
},
{
Sync = {
Key = "\"C=20#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/3E61C9CF-7646-4475-AC89-FB157DA50181.xbel";
};
URIDictionary = {
title = Twitter;
};
URLString = "https://twitter.com/";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "D3893EF3-A885-41F6-A128-BBAC37A2033B";
},
{
Sync = {
Key = "\"C=22#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/C8801D19-7A76-4290-8950-5DA9385F3415.xbel";
};
URIDictionary = {
title = LinkedIn;
};
URLString = "https://www.linkedin.com/";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "47F6045D-4F9A-4856-916A-07CB8889B7E2";
},
{
Sync = {
Key = "\"C=24#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/DF10E9C3-01FA-4EC6-ADE2-4A0B1FECD9EF.xbel";
};
URIDictionary = {
title = "The Weather Channel";
};
URLString = "http://www.weather.com/";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "0DDD3778-437A-4FAE-8529-D389A5122758";
},
{
Sync = {
Key = "\"C=26#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/79C2C180-430C-4092-A4CF-D2B8F4551B1E.xbel";
};
URIDictionary = {
title = Yelp;
};
URLString = "http://www.yelp.com/";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "2FD1AB60-B3A0-44D5-A20D-68CF51A40584";
},
{
Sync = {
Key = "\"C=28#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/63EDC45D-3138-41CF-A617-4178097656F0.xbel";
};
URIDictionary = {
title = TripAdvisor;
};
URLString = "http://www.tripadvisor.com/";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "A6DA8288-409E-4B03-84E4-ACEF9F2B624C";
},
{
Sync = {
Key = "\"C=30#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/40F8D2AF-4F2E-44BE-8250-41E1C7C0F1D9.xbel";
};
URIDictionary = {
title = "ADplus.aspx";
};
URLString = "http://dev.etelmar.net/ADEV_ADplus3-01/ADplus.aspx";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "C5D3ADD4-DB17-421D-BAF5-04927F713BCE";
}
);
Sync = {
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/";
};
Title = BookmarksBar;
WebBookmarkType = WebBookmarkTypeList;
WebBookmarkUUID = "E2EC6281-F0F9-41FA-9C2C-2DC8745F547A";
},
{
Sync = {
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/C81C19F2-E6A6-46C7-9836-DC58A02B46AB/";
};
Title = BookmarksMenu;
WebBookmarkType = WebBookmarkTypeList;
WebBookmarkUUID = "06621BC7-DAA3-4225-8BCB-A65A8E0D0916";
}
);
Sync = {
ServerData = <62706c69 73743030 de010203 04050607 08090a0b 0c0d0e0f 10111213 14151624 25303120 20545054 61675443 54616757 50757368 4b65795d 426f6f6b 6d61726b 42617249 645d486f 6d655552 4c537472 696e675e 426f6f6b 6d61726b 4d656e75 49645c41 63636f75 6e745072 7349645c 42756c6b 52657175 65737473 5953796e 63546f6b 656e5e50 75736854 72616e73 706f7274 735d436c 69656e74 56657273 696f6e5f 10125072 696e6369 70616c55 524c5374 72696e67 5f101653 7570706f 72747353 796e6343 6f6c6c65 6374696f 6e5f100f 496e6974 69616c53 796e6344 6f6e655f 10195365 72766572 446f6573 4e6f7453 7570706f 72745054 6167735f 10314654 3d2d4052 553d3139 30313633 30352d35 3663392d 34333763 2d393566 342d3933 35323162 61643262 65384053 3d33315a 38343032 36333033 36385f10 72687474 70733a2f 2f62616e 73616c76 6b732534 3069636c 6f75642e 636f6d40 7033352d 626f6f6b 6d61726b 732e6963 6c6f7564 2e636f6d 2f383430 32363330 3336382f 626f6f6b 6d61726b 732f3241 36363246 45412d33 3546392d 34344335 2d383742 392d3844 44454245 30453439 31322f5f 104d6874 7470733a 2f2f6261 6e73616c 766b7325 34306963 6c6f7564 2e636f6d 40703335 2d626f6f 6b6d6172 6b732e69 636c6f75 642e636f 6d2f3834 30323633 30333638 2f626f6f 6b6d6172 6b732f5f 10726874 7470733a 2f2f6261 6e73616c 766b7325 34306963 6c6f7564 2e636f6d 40703335 2d626f6f 6b6d6172 6b732e69 636c6f75 642e636f 6d2f3834 30323633 30333638 2f626f6f 6b6d6172 6b732f43 38314331 3946322d 45364136 2d343643 372d3938 33362d44 43353841 30324234 3641422f 5a383430 32363330 333638d2 17181922 54637275 64567369 6d706c65 d41a1b1c 1d1e1f20 20586d61 782d7369 7a655d6d 61782d72 65736f75 72636573 56757064 61746556 696e7365 72741200 a0000010 c80909d3 1b1d1a1f 201e095f 103e4441 5653542d 56312d70 33352d46 543d2d40 52553d31 39303136 3330352d 35366339 2d343337 632d3935 66342d39 33353231 62616432 62653840 533d3333 d1262754 41505344 d428292a 2b2c2d2e 2f5b6170 7362756e 646c6569 6453656e 765f1010 73756273 63726970 74696f6e 2d75726c 5f101072 65667265 73682d69 6e746572 76616c5f 1010636f 6d2e6d65 2e626f6f 6b6d6172 6b735a50 524f4455 4354494f 4e5f1053 68747470 733a2f2f 62616e73 616c766b 73253430 69636c6f 75642e63 6f6d4070 33352d62 6f6f6b6d 61726b73 2e69636c 6f75642e 636f6d2f 38343032 36333033 36382f6d 6d2f7075 73682f72 65676973 74657256 31323030 30301001 5f104d68 74747073 3a2f2f62 616e7361 6c766b73 25343069 636c6f75 642e636f 6d407033 352d626f 6f6b6d61 726b732e 69636c6f 75642e63 6f6d2f38 34303236 33303336 382f7072 696e6369 70616c2f 09090008 0025002a 002f0037 00450053 0062006f 007c0086 009500a3 00b800d1 00e300ff 0133013e 01b30203 02780283 0288028d 0294029d 02a602b4 02bb02c2 02c702c9 02ca02cb 02d202d3 03140317 031c0325 03310335 0348035b 036e0379 03cf03d6 03d80428 04290000 00000000 02010000 00000000 00340000 00000000 00000000 00000000 042a>;
};
Title = "";
WebBookmarkFileVersion = 1;
WebBookmarkType = WebBookmarkTypeList;
WebBookmarkUUID = "FBAA875A-C10A-4744-98BD-DC5EC1D9A009"; }
Before converting any object into json, first check that given object is json convertible or not, you can use following code to check that
if ([NSJSONSerialization isValidJSONObject: plistDict])
{
....
}
Because a JSON Object must be of type NSArray or a NSDictionary while you are passing a NSString.
From the docs :
An object that may be converted to JSON must have the following
properties:
The top level object is an NSArray or NSDictionary.
All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
All dictionary keys are instances of NSString.
Numbers are not NaN or infinity.
Your data structure can be successfully read into a NSDictionary instance. But when you serialize it to JSON it fails because it contains parts that cannot be represented as JSON.
My guess is that it's the data at $.Sync.ServerData. This seems to be binary data. JSON doesn't have an data type for binary data.
Remove this element before you serialize it. Or replace it with something else, e.g. a string with a Base-64 representation of the binary data.
The crucial information is
Invalid type in JSON write (__NSCFData)
JSON does not support NSData type (the value of ServerData), you might send the data as string Base64 encoded.
This is the key:
Invalid type in JSON write (__NSCFData)
You cannot serialise NSData to JSON. Try encoding it to string using base-64 (see this answer to do that).
Do this way may be it helps you
{ NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
self.handmadeEmbDict = [dict6 objectForKey:#"hemb_list"];
[handmadeEmbTable reloadData];
}
- (id)cleanJsonToObject:(id)data {
NSError* error;
if (data == (id)[NSNull null]){
return [[NSObject alloc] init];
}
id jsonObject;
if ([data isKindOfClass:[NSData class]]){
jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
} else {
jsonObject = data;
}
if ([jsonObject isKindOfClass:[NSArray class]]) {
NSMutableArray *array = [jsonObject mutableCopy];
for (int i = (int)array.count-1; i >= 0; i--) {
id a = array[i];
if (a == (id)[NSNull null]){
[array removeObjectAtIndex:i];
} else {
array[i] = [self cleanJsonToObject:a];
}
}
return array;
} else if ([jsonObject isKindOfClass:[NSDictionary class]]) {
NSMutableDictionary *dictionary = [jsonObject mutableCopy];
for(NSString *key in [dictionary allKeys]) {
id d = dictionary[key];
if (d == (id)[NSNull null]){
dictionary[key] = #"";
} else {
dictionary[key] = [self cleanJsonToObject:d];
}
}
return dictionary;
} else {
return jsonObject;
}
}
Swift 2
if let path = NSBundle.mainBundle().pathForResource("try", ofType: "json")
{
do {
let jsonData = try NSData(contentsOfFile:
path, options: NSDataReadingOptions.MappedRead)
let dict = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableLeaves)
let rootDict = dict
Print(rootDict)
catch
{
}
}

Resources