-3

I want to parse JSON from url and NSLog it. this is my url : http://api.kivaws.org/v1/loans/search.json?status=fundraising

and this is my code . when I run my code this crashing.....

NSURL * url=[NSURL URLWithString:@"http://api.kivaws.org/v1/loans/search.json?status=fundraising"];
NSData* data = [NSData dataWithContentsOfURL:url];
NSError* error;
NSDictionary* json = [NSJSONSerialization
                          JSONObjectWithData:data options:kNilOptions
                          error:&error];

NSLog(@"%@",json);

please help me about it.... this is my crash error :

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000104827f35 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x0000000106905bb7 objc_exception_throw + 45
    2   CoreFoundation                      0x0000000104827e6d +[NSException raise:format:] + 205
    3   Foundation                          0x00000001065aa1bf +[NSJSONSerialization JSONObjectWithData:options:error:] + 67
    4   json                                0x00000001046608b9 -[ViewController viewDidLoad] + 185
    5   UIKit                               0x00000001052d3a90 -[UIViewController loadViewIfRequired] + 738
    6   UIKit                               0x00000001052d3c8e -[UIViewController view] + 27
    7   UIKit                               0x00000001051f2ca9 -[UIWindow addRootViewControllerViewIfPossible] + 58
    8   UIKit                               0x00000001051f3041 -[UIWindow _setHidden:forced:] + 247
    9   UIKit                               0x0000000112eac7b0 -[UIWindowAccessibility _orderFrontWithoutMakingKey] + 68
    10  UIKit                               0x00000001051ff72c -[UIWindow makeKeyAndVisible] + 42
    11  UIKit                               0x00000001051aa061 -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 2628
    12  UIKit                               0x00000001051acd2c -[UIApplication _runWithMainScene:transitionContext:completion:] + 1350
    13  UIKit                               0x00000001051abbf2 -[UIApplication workspaceDidEndTransaction:] + 179
    14  FrontBoardServices                  0x000000010b6692a3 __31-[FBSSerialQueue performAsync:]_block_invoke + 16
    15  CoreFoundation                      0x000000010475d53c __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12
    16  CoreFoundation                      0x0000000104753285 __CFRunLoopDoBlocks + 341
    17  CoreFoundation                      0x0000000104753045 __CFRunLoopRun + 2389
    18  CoreFoundation                      0x0000000104752486 CFRunLoopRunSpecific + 470
    19  UIKit                               0x00000001051ab669 -[UIApplication _run] + 413
    20  UIKit                               0x00000001051ae420 UIApplicationMain + 1282
    21  json                                0x0000000104660ca3 main + 115
    22  libdyld.dylib                       0x0000000107089145 start + 1
    23  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
MmD
  • 2,044
  • 5
  • 22
  • 41
  • 4
    Your `data` parameter is `nil`. You need to fix that, or handle it. – Abizern Dec 28 '14 at 12:41
  • the exception says that `data` is `nil`. – Daniel A. White Dec 28 '14 at 12:41
  • @Abizern I know why my data is nil... NSData* data = [NSData dataWithContentsOfURL:url]; is wrong??? – MmD Dec 28 '14 at 12:43
  • 2
    And fetching a URL synchronously is a bad idea. – Abizern Dec 28 '14 at 12:49
  • @Abizern What I do when I want give value with son from server??? please guide me.... – MmD Dec 28 '14 at 12:53
  • 3
    There are much better methods for fetching data than `dataWithContentsOfURL` such as `sendAsynchronousRequest`. – zaph Dec 28 '14 at 12:53
  • @Zaph please tell me with sample code or source!!! – MmD Dec 28 '14 at 12:54
  • Read the Apple documentation, SO has many code examples. One of the advantages is an error parameter, use it. – zaph Dec 28 '14 at 13:10
  • @Zaph I want to get json from server NSJSONSerialization is bad method??? – MmD Dec 28 '14 at 13:25
  • 1
    @mamal10 There's nothing wrong with using `NSJSONSerialization` to parse the response. But you're using `NSData dataWithContentsOfURL` to get the data, which _is_ bad because if it fails, it doesn't tell you why it failed. If you used one of the asynchronous techniques (search for "NSURLConnection sendAsynchronousRequest example" or "NSURLSession dataTaskWithURL example" and you'll probably see good examples), they (a) give informative `NSError` objects you can examine if the request fails; and (b) are asynchronous, addressing an egregious, though completely unrelated, problem in your code. – Rob Dec 28 '14 at 13:44

1 Answers1

-1

If you need to know the reason for a failure, start with

NSError* error = nil;    
NSData* data = [NSData dataWithContentsOfURL:url options: nil error:&error]:

Then if this fails, you can look at the error by using

NSLog@"Error description = %@", [error localizedDescription];

Also, as others have said, you should change your code so that the URL is being fetched asynchronously. Instead, for non-file URLs, consider using the dataTaskWithURL:completionHandler: method of the NSSession class. See URL Loading System Programming Guide for details.

narco
  • 830
  • 8
  • 21
  • 1
    Checking the error parameter is incorrect, it is **not** guaranteed to be nil on success. Instead one must check the return value, in this case data, for nil. – zaph Dec 28 '14 at 13:35
  • @Zaph ??? I didn't say that it was. What I wrote was "If you need to know the reason for failure". And the official documentation uses almost the exact same wording: "If you need to know what was the reason for failure, use dataWithContentsOfFile:options:error:" so I hardly think I deserve a down vote. – narco Dec 28 '14 at 14:36
  • @zaph Who said it was a check for failure??? I very clearly said "If you need to know the reason for failure". The question asker knows that his data is nil (he says so (in broken english) in the comments), and his question is "why"?, so I gave him some help for that. – narco Dec 28 '14 at 14:56
  • OK, well if one person has been confused by the intent of my answer (which was to show him how to find the reason for a known failure, as he asked), then I'm guessing more will, so I'll change it. How do you like it now? – narco Dec 28 '14 at 15:20
  • Well I was thinking that you would otherwise log something to the effect of there being no error, instead of logging the description of a non existing error. But yes, it is not vital, and I had already taken out before your last comment. Do you agree that my answer is (at least now) a way that the questioner could proceed toward finding the cause of their unexpected nil data value? – narco Dec 28 '14 at 22:27
  • I know. I think the confusion here is that the question was not how he should deal with all eventualities in his final program (which your answers have been addressing), but rather, he was asking how he can figure out what he is doing wrong at the moment, which is what I was trying to help with. He already knows he is getting an error, he already knows his data is nil when it shouldn't be, he wants to know why. He hasn't used the version of the method that he can get an error description from, so I told him how to do that. This should help him solve his current problem. Do you see it now? – narco Dec 28 '14 at 23:25
  • The rather standard pattern is: `NSError *error;` `NSData *data = [NSData dataWithContentsOfURL:url options:nil error:&error];` `if (data == nil) {` `NSLog@"Error; %@", error)` `}` – zaph Dec 28 '14 at 23:25
  • Presumably you edited you last reply, I had already replied, and my answer to it now appears before yours. – narco Dec 28 '14 at 23:38