Search code examples
objective-ciosjsonnsdictionarynsdata

Not able to read JSON from service


I am implementing forget password service in which I would pass an email address and it would return JSON to acknowledge about the sent email. The issue is that I am unable to read the response string in json, and my exception message is shown that data parameter is nil, but if I view the url in my web browser the service looks fine as mentioned below. my code is:

NSURL *url = [LokalmotionCommonTask getURLForgotPassword:emailFieldTxt.text];

    NSData* data = [NSData dataWithContentsOfURL: url];

    @try {
        NSError* error;
        NSDictionary* jsonDict = [NSJSONSerialization 
                                  JSONObjectWithData:data //1
                                  options:0 
                                  error:&error];

        NSLog(@"%@", [jsonDict objectForKey:@"response"]);
    }
    @catch (NSException *exception) {
        NSLog(@"forgot password exception: %@: %@", [exception name], [exception reason]);
    }

and the service response I get in my web browser is like this:

{"status":400,"response":"Your request to change password is already sent. Please check your email."}

Exception:

forgot password exception: NSInvalidArgumentException: data parameter is nil

Solution

  • in Objective-C exceptions are only used for fatal errors, not recoverable errors. Instead just check for nil data:

    If you need to know what was the reason for failure, use:

    NSError* error;
    NSURL *url = [LokalmotionCommonTask getURLForgotPassword:emailFieldTxt.text];
    NSData* data = [NSData dataWithContentsOfURL: url options:NULL error:&error];
    if (data) {
        NSDictionary* jsonDict = [NSJSONSerialization 
                                  JSONObjectWithData:data //1
                                  options:0 
                                  error:&error];
        NSLog(@"%@", [jsonDict objectForKey:@"response"]);
    }
    else {
        NSLog(@"forgot password error, %@", [error localizedFailureReason]);
    }
    

    There is a naming convention error: getURLForgotPassword:
    A method name that begins with "get" implies that there will be a return by reference parameter. Better to just name the method: forgotPasswordURL:

    These two things, exceptions and accessors prefixed with get are a basic difference from Jave.