Obj-C: Application crashing while converting NSDictionary to JSON - ios

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
{
}
}

Related

relations using CoreDatato-many key not allowed here

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.

Write auto increment id

I'm working on a iOs program in Swift, I'm using Core Data, I tried to found how to have a auto increment id, I found this:
But no issues here, so I tried to see how to write a self auto increment attribute:
I added a new attribute in my .xcdatamodeld file named "id", I found a solution in Objective-C:
https://stackoverflow.com/a/22503259/5315947
But I don't know how to parse it into Swift2
My code:
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext
let newDemande = NSEntityDescription.insertNewObjectForEntityForName("Demandes", inManagedObjectContext: context)
newDemande.setValue(soapRequest.xmlString, forKey: "xml")
newDemande.setValue(1, forKey: "statutenvoie")
do {
try context.save()
} catch {
print("erreur data")
}
do {
let request = NSFetchRequest(entityName: "Demandes")
let results = try context.executeFetchRequest(request)
if results.count > 0 {
for item in results as! [NSManagedObject]{
let xml = item.valueForKey("xml")
let statutenvoie = item.valueForKey("statutenvoie")
print(item.objectID)
print(xml!, statutenvoie!)
}
}
} catch {
print("erreur data")
}
UUID error:
code:
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext
let newDemande = NSEntityDescription.insertNewObjectForEntityForName("Demandes", inManagedObjectContext: context)
newDemande.setValue(NSUUID().UUIDString, forKey: "id")
newDemande.setValue(soapRequest.xmlString, forKey: "xml")
newDemande.setValue(1, forKey: "statutenvoie")
do {
try context.save()
} catch {
print("erreur data")
}
do {
let request = NSFetchRequest(entityName: "Demandes")
let results = try context.executeFetchRequest(request)
if results.count > 0 {
for item in results as! [NSManagedObject]{
let id = item.valueForKey("id")
let xml = item.valueForKey("xml")
let statutenvoie = item.valueForKey("statutenvoie")
// print(item.objectID)
print(id!, xml!, statutenvoie!)
}
}
} catch {
print("erreur data")
}
error:
2016-01-11 16:33:18.921 ...[2694:108875] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "id"; desired type = NSNumber; given type = __NSCFString; value = 781EFF10-A9F1-4710-98C1-6D342B2EB480.'
*** First throw call stack:
(
0 CoreFoundation 0x0000000110a2be65 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x00000001132f8deb objc_exception_throw + 48
2 CoreData 0x00000001105c77b0 _PFManagedObject_coerceValueForKeyWithDescription + 2864
3 CoreData 0x000000011059f621 _sharedIMPL_setvfk_core + 177
4 ... 0x000000010ff690e5 _TFC7...29DemandeGratuiteViewController7ValiderfS0_FPSs9AnyObject_T_ + 4757
5 ... 0x000000010ff6aaa6 _TToFC7...29DemandeGratuiteViewController7ValiderfS0_FPSs9AnyObject_T_ + 54
6 UIKit 0x0000000112285e73 _UIGestureRecognizerSendTargetActions + 153
7 UIKit 0x00000001122824e5 _UIGestureRecognizerSendActions + 162
8 UIKit 0x00000001122804e2 -[UIGestureRecognizer _updateGestureWithEvent:buttonEvent:] + 843
9 UIKit 0x00000001122889a0 ___UIGestureRecognizerUpdate_block_invoke904 + 79
10 UIKit 0x000000011228883e _UIGestureRecognizerRemoveObjectsFromArrayAndApplyBlocks + 342
11 UIKit 0x0000000112276101 _UIGestureRecognizerUpdate + 2634
12 UIKit 0x0000000111e0df8a -[UIWindow _sendGesturesForEvent:] + 1137
13 UIKit 0x0000000111e0f1c0 -[UIWindow sendEvent:] + 849
14 UIKit 0x0000000111dbdb66 -[UIApplication sendEvent:] + 263
15 UIKit 0x0000000111d97d97 _UIApplicationHandleEventQueue + 6844
16 CoreFoundation 0x0000000110957a31 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
17 CoreFoundation 0x000000011094d95c __CFRunLoopDoSources0 + 556
18 CoreFoundation 0x000000011094ce13 __CFRunLoopRun + 867
19 CoreFoundation 0x000000011094c828 CFRunLoopRunSpecific + 488
20 GraphicsServices 0x0000000114c2dad2 GSEventRunModal + 161
21 UIKit 0x0000000111d9d610 UIApplicationMain + 171
22 ... 0x000000010ff352cd main + 109
23 libdyld.dylib 0x0000000113e0a92d start + 1
24 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
Error:
2016-01-12 09:13:03.726 ...[576:7439] CoreData: error: -addPersistentStoreWithType:SQLite configuration:(null) URL:file:///Users/informatiqueresponis/Library/Developer/CoreSimulator/Devices/314EFA4E-CC21-45A0-B3FD-FA486D52BB99/data/Containers/Data/Application/B0AB216F-D9B4-408D-ADB5-92BE2D333F62/Documents/SingleViewCoreData.sqlite options:(null) ... returned error Error Domain=NSCocoaErrorDomain Code=134100 "(null)" UserInfo={metadata={
NSPersistenceFrameworkVersion = 641;
NSStoreModelVersionHashes = {
Demandes = <e6fa8ed7 47097048 95c90274 cbc26ea7 decd6ea3 12e0df98 cd0d3cec da84d5ff>;
};
NSStoreModelVersionHashesVersion = 3;
NSStoreModelVersionIdentifiers = (
""
);
NSStoreType = SQLite;
NSStoreUUID = "7C53DEAF-C47E-446B-913E-060946C728B0";
"_NSAutoVacuumLevel" = 2;
}, reason=The model used to open the store is incompatible with the one used to create the store} with userInfo dictionary {
metadata = {
NSPersistenceFrameworkVersion = 641;
NSStoreModelVersionHashes = {
Demandes = <e6fa8ed7 47097048 95c90274 cbc26ea7 decd6ea3 12e0df98 cd0d3cec da84d5ff>;
};
NSStoreModelVersionHashesVersion = 3;
NSStoreModelVersionIdentifiers = (
""
);
NSStoreType = SQLite;
NSStoreUUID = "7C53DEAF-C47E-446B-913E-060946C728B0";
"_NSAutoVacuumLevel" = 2;
};
reason = "The model used to open the store is incompatible with the one used to create the store";
}
2016-01-12 09:13:03.730 ...[576:7439] Unresolved error Error Domain=YOUR_ERROR_DOMAIN Code=9999 "Failed to initialize the application's saved data" UserInfo={NSLocalizedDescription=Failed to initialize the application's saved data, NSLocalizedFailureReason=There was an error creating or loading the application's saved data., NSUnderlyingError=0x7fded60cdae0 {Error Domain=NSCocoaErrorDomain Code=134100 "(null)" UserInfo={metadata={
NSPersistenceFrameworkVersion = 641;
NSStoreModelVersionHashes = {
Demandes = <e6fa8ed7 47097048 95c90274 cbc26ea7 decd6ea3 12e0df98 cd0d3cec da84d5ff>;
};
NSStoreModelVersionHashesVersion = 3;
NSStoreModelVersionIdentifiers = (
""
);
NSStoreType = SQLite;
NSStoreUUID = "7C53DEAF-C47E-446B-913E-060946C728B0";
"_NSAutoVacuumLevel" = 2;
}, reason=The model used to open the store is incompatible with the one used to create the store}}}, [NSLocalizedDescription: Failed to initialize the application's saved data, NSLocalizedFailureReason: There was an error creating or loading the application's saved data., NSUnderlyingError: Error Domain=NSCocoaErrorDomain Code=134100 "(null)" UserInfo={metadata={
NSPersistenceFrameworkVersion = 641;
NSStoreModelVersionHashes = {
Demandes = <e6fa8ed7 47097048 95c90274 cbc26ea7 decd6ea3 12e0df98 cd0d3cec da84d5ff>;
};
NSStoreModelVersionHashesVersion = 3;
NSStoreModelVersionIdentifiers = (
""
);
NSStoreType = SQLite;
NSStoreUUID = "7C53DEAF-C47E-446B-913E-060946C728B0";
"_NSAutoVacuumLevel" = 2;
}, reason=The model used to open the store is incompatible with the one used to create the store}]
(lldb)
Still confusing with the example you gave in the comment. My answer is based on my understand that you want an auto increase field - id, when next time you insert a new entry.
If you have two fields, i.e. xmlString & id. Then first you do everytime is a fetch request with SortDescriptor and setFetchLimit = 1. If the result is empty, you insert a new entry with id = 1. Otherwise, insert a new entry with id = oldId + 1.
I intentionally doesn't provide any code, because I'm not sure what you really want.
BTW, you'd better to use custom model, i.e. NSManagedObject generated by XCode, rather than the current newDemande.setValue(value, forKey: "key")
EDIT
Example code provided:
// Initialize Fetch Request
let fetchRequest = NSFetchRequest(entityName: "Demandes")
// Sort Descriptor
var idDescriptor: NSSortDescriptor = NSSortDescriptor(key: "id", ascending: false)
fetchRequest.sortDescriptors = [idDescriptor] // Note this is a array, you can put multiple sort conditions if you want
// Set limit
fetchRequest.fetchLimit = 1
var newId = 0; // Default to 0, so that you can check if do catch block went wrong later
do {
let results = try self.managedObjectContext.executeFetchRequest(fetchRequest)
//Compute the id
if(results.count == 1) newId = results[0].id + 1 // slightly odd notation here, .id can be used if you use custom model. or you can use .valueForKey("id")
else newId = 1
} catch {
let fetchError = error as NSError
print(fetchError)
}
// Do the new insert afterwards
I think you are sending a string value (781EFF10-A9F1-4710-98C1-6D342B2EB480) and core data is expecting an NSNumber (Int). Obviously, 781EFF10-A9F1-4710-98C1-6D342B2EB480 is not a number.
Core data always stores Int (Doubles, Float, etc...) values as NSNumber, for example:
let intValue
let intValueInNSNumber = NSNumber(int: intValue)
The difference is that intValue (Int) is a primitive type, while NSNumber is an object.
What's the type for the attribute "id"?
Because, if the attribute is of type "Int" you will have to change it to "String" and it should work.

Crash while using CFHostCreateWithName: "Attempt to start the Thread again"

help!
I met a crash when i try to get the addresses for the give hostname;
the crash log shows like this:
1 libobjc.A.dylib 0x0000000197d180e4 objc_exception_throw + 56
2 CoreFoundation 0x0000000186044218 -[NSException initWithCoder:]
3 Foundation 0x0000000186e9528c -[NSThread start] + 136
4 ZFirewall7.dylib 0x0000000105e4d768 -[FiPSettingsManager doHostStuff:] + 1124
5 ZFirewall7.dylib 0x0000000105e48424 _ZL23my_CFHostCreateWithNamePPK13__CFAllocatorPPK10__CFString + 164
6 Upload 0x000000010220d1c0 +[UploadUtil addressesForHostname:] (UploadUtil.m:277)
7 Upload 0x000000010220d120 +[UploadUtil addressForHostname:] (UploadUtil.m:267)
....
*** -[NSThread start]: attempt to start the thread again
and my code is:
+(NSArray *)addressesForHostname:(NSString *)hostname
{
// Get the addresses for the given hostname.
CFHostRef hostRef = CFHostCreateWithName(kCFAllocatorDefault, (__bridge CFStringRef)hostname);
BOOL isSuccess = CFHostStartInfoResolution(hostRef, kCFHostAddresses, nil);
if (!isSuccess)
{
CFRelease(hostRef);
return nil;
}
CFArrayRef addressesRef = CFHostGetAddressing(hostRef, nil);
if (addressesRef == nil)
{
CFRelease(hostRef);
return nil;
}
// Convert these addresses into strings.
char ipAddress[INET6_ADDRSTRLEN];
NSMutableArray *addresses = [NSMutableArray array];
CFIndex numAddresses = CFArrayGetCount(addressesRef);
for (CFIndex currentIndex = 0; currentIndex < numAddresses; currentIndex++) {
struct sockaddr *address = (struct sockaddr *)CFDataGetBytePtr(CFArrayGetValueAtIndex(addressesRef, currentIndex));
if (address == nil)
{
CFRelease(hostRef);
return nil;
}
getnameinfo(address, address->sa_len, ipAddress, INET6_ADDRSTRLEN, nil, 0, NI_NUMERICHOST);
[addresses addObject:[NSString stringWithCString:ipAddress encoding:NSASCIIStringEncoding]];
}
CFRelease(hostRef);
return addresses;
}
this function do called by several threads, and the doc of CFHostCreateWithName says that it is thread safe, now i have no idea about how to solve this problem.
help!

iOS Crash Log NSObject doesNotRecognizeSelector: - at which line?

I have recorded a crash of my app, but the last line in my app (5 Control) points just to the method begin. How do I know in which line the problem is?
0 CoreFoundation 0x185f0af50 __exceptionPreprocess + 132
1 libobjc.A.dylib 0x1924141fc objc_exception_throw + 60
2 CoreFoundation 0x185f0fc04 -[NSObject(NSObject) doesNotRecognizeSelector:] + 220
3 CoreFoundation 0x185f0d930 ___forwarding___ + 912
4 CoreFoundation 0x185e2d5dc _CF_forwarding_prep_0 + 92
5 Control 0x10005acb4 -[PaymillPaymentService handleTransactionListRequest:] (PaymillPaymentService.m:211)
6 Foundation 0x186a7416c __103+[__NSOperationInternal _observeValueForKeyPath:ofObject:changeKind:oldValue:newValue:indexes:context:]_block_invoke96 + 28
7 libdispatch.dylib 0x1929ec014 _dispatch_call_block_and_release + 24
8 libdispatch.dylib 0x1929ebfd4 _dispatch_client_callout + 16
9 libdispatch.dylib 0x1929f32b8 _dispatch_root_queue_drain + 556
10 libdispatch.dylib 0x1929f34fc _dispatch_worker_thread2 + 76
11 libsystem_pthread.dylib 0x192b816bc _pthread_wqthread + 356
12 libsystem_pthread.dylib 0x192b8154c start_wqthread + 4
Here the [lengthy] method code. I see a couple of places where I can add the check but how to I know it for sure that I fixed the issue? The problem is sporadical and I cannot reproduce it easily.
- (void)handleTransactionListRequest:(ServiceRequest *)serviceRequest
{
LRURLRequestOperation* operation = serviceRequest.operation;
NSHTTPURLResponse *response = (NSHTTPURLResponse *)operation.URLResponse;
if (response.statusCode == 200)
{
if (operation.responseData)
{
NSError *parserError = nil;
NSDictionary *data = [NSJSONSerialization JSONObjectWithData:operation.responseData options:0 error:&parserError];
//NSLog(#"%#", data);
if (!parserError)
{
NSArray* transactions = [data objectForKey:#"data"];
if (0 == serviceRequest.currentOffset)
{
NSNumber* totalCountObj = [data objectForKey:#"data_count"];
serviceRequest.totalCount = [totalCountObj intValue];
}
int loadedCount = 0;
if (transactions)
{
for (id object in transactions)
{
TransactionInfo* info = [self createTransactionFrom:object];
[serviceRequest.transactionList addTransaction:info];
[info release];
loadedCount++;
}
}
if (loadedCount + serviceRequest.currentOffset >= serviceRequest.totalCount)
{
if ([serviceRequest.delegate respondsToSelector:#selector(transactionListLoadingComplete:)])
[serviceRequest.delegate transactionListLoadingComplete:serviceRequest];
serviceRequest.transactionList.timeStamp = [[NSDate date] timeIntervalSince1970];
NSLog(#"COMPLETE: %d transaction loaded ", serviceRequest.totalCount);
}
else
{
serviceRequest.currentOffset += loadedCount;
bool needToContinue = YES;
if ([serviceRequest.delegate respondsToSelector:#selector(transactionListLoadingContinue:)])
needToContinue = [serviceRequest.delegate transactionListLoadingContinue];
if (needToContinue)
{
[self continueRetrievingTransactionListFor:serviceRequest];
NSLog(#"CONTINUE: %d of %d loaded ", serviceRequest.currentOffset, serviceRequest.totalCount);
}
}
return; // all OK cases
}
}
}
if ([serviceRequest.delegate respondsToSelector:#selector(transactionListLoadingFailed:with:)])
[serviceRequest.delegate transactionListLoadingFailed:serviceRequest with:response.statusCode];
NSLog(#"ERROR: Loading Transactions Response Code: %ld", (long)response.statusCode);
}
Short Answer:
You are sending a message to an object that cannot validly respond to it. The stack trace is telling you that when you make the call [PaymillPaymentService handleTransactionListRequest:] that PaymillPaymentService cannot accept handleTransactionListRequest.
Long answer:
Look at the stack trace here:
5 Control 0x10005acb4 -[PaymillPaymentService handleTransactionListRequest:] (PaymillPaymentService.m:211)
This is telling you that in the file PaymillPaymentService.m on line 211 you are sending PaymillPaymentService the message handleTransactionListRequest to which it cannot validly respond. In your discussion with rmaddy, Hot Licks, and Paulc11 you mentioned that line 211 is the function entry for handleTransactionListRequest (in whatever file it resides). If that's the case it is coincidental.
If you want further follow up you need to post PaymillPaymentService.m and ensure that you include all the line numbers.

Getting CocoaLibSpotify error in SPPlaylist.m

When I try to build my project i get the following error on line 827
/PATH_TO_PROJECT/Libs/CocoaLibSpotify/Model/SPPlaylist.m:827:25: Implicit conversion of Objective-C pointer type 'AVAssetTrack *' to C pointer type 'sp_track *' (aka 'struct sp_track *') requires a bridged cast
Here is the code where the error occurs:
805 -(void)addItems:(NSArray *)newItems atIndex:(NSUInteger)index callback:(SPErrorableOperationCallback)block {
806
807 SPDispatchAsync(^{
808
809 if (newItems.count == 0) {
810 dispatch_async(dispatch_get_main_queue(), ^{
811 if (block) block([NSError spotifyErrorWithCode:SP_ERROR_INVALID_INDATA]);
812 });
813 return;
814 }
815
816 sp_track **tracks = malloc(sizeof(sp_track *) * newItems.count);
817
818 // libSpotify iterates through the array and inserts each track at the given index,
819 // which ends up reversing the expected order. Defeat this by constructing a backwards
820 // array.
821 for (int currentTrack = (int)newItems.count - 1; currentTrack >= 0; currentTrack--) {
822
823 sp_track *track;
824 id item = [newItems objectAtIndex:currentTrack];
825
826 if ([item isKindOfClass:[SPTrack class]])
827 track = [item track];
828 else
829 track = [(SPTrack *)((SPPlaylistItem *)item).item track];
830
831 tracks[currentTrack] = track;
832 }
833 sp_track *const *trackPointer = tracks;
834
835 if (block)
836 [self.addCallbackStack addObject:block];
837
838 sp_error errorCode = sp_playlist_add_tracks(self.playlist, trackPointer, (int)newItems.count, (int)index, self.session.session);
839 free(tracks);
840 tracks = NULL;
841
842 NSError *error = nil;
843 if (errorCode != SP_ERROR_OK)
844 error = [NSError spotifyErrorWithCode:errorCode];
845
846 if (error && block) {
847 [self.addCallbackStack removeObject:block];
848 dispatch_async(dispatch_get_main_queue(), ^{ block(error); });
849 }
850 });
851 }
Thanks for your help!
The error is pretty self-explanatory - you need to make a bridged cast.
track = (__bridge sp_track *)[item track];
or
track = [(SPPlaylistItem *)item track];

Resources