getting null pointer exception in ios using json in objective c - ios

I tried below code like this ,
NSDictionary * callDict = meetingdictparams;
// convert your dictionary to NSData
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:callDict options:kNilOptions error:nil];
// this is your service request url
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:meetingupdateurlparams]];
// set the content as format
[request setHTTPMethod:#"POST"];
[request setHTTPBody: jsonData];
// this is your response type
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSError *err;
NSURLResponse *response;
// send the synchronous connection
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
// here add your server response NSJSONSerialization
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
NSLog(#"json array is %#",jsonArray);
// if u want to check the data in console
NSString *tmp=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#", tmp);
getting errror like this,
java.lang.NullPointerException
status code:503
backenederror
I checked that server url in postman..it's working properly....
and I am sending parameters as this..
NSDictionary *dictionary=[[NSDictionary alloc]initWithObjectsAndKeys:_MeetingTypeId,#"meetingTyp",Meetingtitletxtfld.text,#"meetinTitle",Meetingdistxtfld.text,#"meetDescription",_Starttimestr,#"startTym",Meetinglengthtxtfld.text,#"hours",Useridstr,#"meetOwnId",_ProjId,#"projectId",[[meetDate componentsSeparatedByString: #" "]objectAtIndex:0],#"meetDate",_MeetingId,#"meetingId",_ConfOwnerId,#"ConferRoomId",nil];
NSLog(#"all key values are %#",dictionary);
so,anyone can help in this issuance..thanks in advance....

Related

NSJSONSerialization get error "index 1 beyond bounds for empty array"

sometimes I get error "index 1 beyond bounds for empty array" at this line
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
This is my full code
+ (NSDictionary *)getJson: (NSString *)strURL parameters:(NSDictionary *)parameters{
NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:15.0];
NSDictionary *headers = #{ #"content-type": #"application/json",
#"cache-control": #"no-cache",
#"postman-token": #"374a4b6f-b660-78f2-78bf-e22cf0156d8d"};
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];*
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:aData options: NSJSONReadingMutableContainers error:&error];
return json;
}
Sometimes I get error, Sometimes not. I don't understands ? please help me, thanks everyone.
Whenever you get an error like the above, try the following:
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:aData options: NSJSONReadingMutableContainers error:&error];
if (error)
{
//1. See what the error says
NSLog(error.localizedDescription);
//2. Convert the original data into a string
NSString *jsonString = [[NSString alloc] initWithData:aData encoding: NSUTF8StringEncoding];
//Now take this string and validate it as a JSON at a place like http://jsonlint.com/
}
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: url
cachePolicy: defaultCachePolicy
timeoutInterval: defaultTimeoutInSeconds];
plz change your cachePolicy with defaultCachePolicy and try :)

How to pass dictionary as a parameter in JSON

I am new to json, I want to pass dictionary as a parameter along with the url to server, how it can be done while method is post ? Ihad tried sample codes but not found my exact solution.below is my sample code
NSMutableDictionary *callDict =[[NSMutableDictionary alloc] init];
[callDict setObject:#"messages-getModuleMessages" forKey:#"call"];
[callDict setObject:FB_API_KEY forKey:#"accessSecret"];
NSString *x=[FBUserManager sharedUserManager].authToken;
[callDict setObject:x forKey:#"authToken"];
[callDict setObject:#"json" forKey:#"format"];
[callDict setObject:#"inbox" forKey:#"callType"];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.fretbay.com/fr/private/api/rest-server.php?",calldict]];//here recieving warning
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err]; // here parsing the array
NSDictionary *parameters = #{
#"call": #"messages-getModuleMessages",
#"accessSecret": FB_API_KEY,
#"authToken": [FBUserManager sharedUserManager].authToken,
#"format": #"json",
#"inbox":#"callType"
};
NSData *data = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.fretbay.com/fr/private/api/rest-server.php?"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *dataTask = [session uploadTaskWithRequest: request
fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#", json);
}];
[dataTask resume];
assume that these are your strings
NSString *messages-getModuleMessages=#"messages-getModuleMessages";
NSString * authtincateToken=#"WWc3ZFZCcEtWcGxLTk1hZHhEb2hMelFNZzdGcXgwdTBxeU51NWFwUE44TnkrcnF5SCtSMDxxxxxxx";
NSString *accessSecretkey =#"WWc3ZFZCcEtWcGxLTk1hZHhEb2hMelFNZzdGcXgwdTBxeU51NWFwUE44TnkrcnF5SCtxxxxxxxx";
NSString *inboxvalue =#"hai thios is textmessage";
// this is your dictionary value are you passed
NSDictionary * callDict = [NSDictionary dictionaryWithObjectsAndKeys:messages-getModuleMessages,#"call",authtincateToken,#"authToken", accessSecretkey, #"accessSecret",inboxvalue,#"calotype",#"json",#"format",nil];
// convert your dictionary to NSData
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:callDict options:kNilOptions error:nil];
// this is your service request url
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://xxxxxxxx"]];
// set the content as format
[request setHTTPMethod:#"POST"];
[request setHTTPBody: jsonData];
// this is your response type
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSError *err;
NSURLResponse *response;
// send the synchronous connection
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
// here add your server response NSJSONSerialization
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
// if u want to check the data in console
NSString *tmp=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#", tmp);
Put following method to Call WebService
- (void) callWebservice_Block : (NSDictionary *) jsonDict :(void(^)(NSDictionary * dic, NSError * err))responseHandler{
NSError * err;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&err];
NSString * jsonRequest = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];;
NSLog(#"jsonRequest is %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"Past your URL Here"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
responseHandler (nil,error);
} else {
NSDictionary * returnDict = [NSJSONSerialization JSONObjectWithData:data
options: NSJSONReadingMutableContainers
error: &error];
responseHandler (returnDict,nil);
}
}];}
you can Call Method via following way.
NSDictionary *jsonDict = [NSDictionary dictionaryWithObjectsAndKeys:#"FirstValue",#"FirstKey",#"SecondValue",#"SecondKey", nil];
[self callWebservice_Block:jsonDict :^(NSDictionary *dic, NSError *err) {
if(!err){
NSLog(#"Got Response :- %#",dic);
}
}];

How can i post json string to server

This is json string that I have to post...
{
"data": {
"description": "",
"current_value": "",
"serialno": "",
"condition": "",
"category": "category",
"purchase_value": "",
"new_or_used": "",
"gift_or_purchase": "",
"image": ""
},
"subtype": "fd3102d8-bc19-424b-bca2-774a8fd7ea6f"
}
How to post as JSON?
Surely this Q us a duplicate, but here's full example code, as one long routine. Just copy and paste.
First set up the JSON...
-(void)sendTestJsonCommand
{
NSMutableDictionary *dict = #{
#"heights":#"4_5_7",
#"score":#"4",
#"title":#"Some Title",
#"textBody":#"Some Long Text",
#"happy":#"y"
}.mutableCopy;
NSError *serr;
NSData *jsonData = [NSJSONSerialization
dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&serr];
if (serr)
{
NSLog(#"Error generating json data for send dictionary...");
NSLog(#"Error (%#), error: %#", dict, serr);
return;
}
NSLog(#"Successfully generated JSON for send dictionary");
NSLog(#"now sending this dictionary...\n%#\n\n\n", dict);
Next, correctly asynchronously send the command and json to your server...
#define appService [NSURL \
URLWithString:#"http://www.corp.com/apps/function/user/pass/id/etc"]
// Create request object
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:appService];
// Set method, body & content-type
request.HTTPMethod = #"POST";
request.HTTPBody = jsonData;
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:
[NSString stringWithFormat:#"%lu",
(unsigned long)[jsonData length]] forHTTPHeaderField:#"Content-Length"];
// you would almost certainly use MBProgressHUD at this point
// to display some sort of spinner or similar action on the UX
Finally, (A) connect correctly using NSURLConnection, and (B) correctly interpret the information which comes back to you from your server.
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *r, NSData *data, NSError *error)
{
if (!data)
{
NSLog(#"No data returned from server, error ocurred: %#", error);
NSString *userErrorText = [NSString stringWithFormat:
#"Error communicating with server: %#", error.localizedDescription]
return;
}
NSLog(#"got the NSData fine. here it is...\n%#\n", data);
NSLog(#"next step, deserialising");
NSError *deserr;
NSDictionary *responseDict = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&deserr];
NSLog(#"so, here's the responseDict\n\n\n%#\n\n\n", responseDict);
// LOOK at that output on your console to learn how to parse it.
// to get individual values example blah = responseDict[#"fieldName"];
}];
}
Hope it saves someone some typing!
Use following shnchronous request, you can use asynchronous request as well,
NSError *error;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:<Your API URL>]];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:<Your Mutable NSDictionary> options:NSJSONReadingMutableContainers error:&error];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//NSLog(#"results string = %#",[[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]);
NSDictionary *temp= [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];// This will convert Data to Json format
As per my point of view you can Use NSURLSeession with Asyn request (Try to implement NSURLSession)
NSData *postData =[NSJSONSerialization dataWithJSONObject:Data options:0 error:&error];
if (!error)
{
NSString *urlpart = [NSString stringWithFormat:#“Your URL];
NSURL *requestUrl = [NSURL URLWithString:urlpart];
NSMutableURLRequest *URLRequest = [NSMutableURLRequest requestWithURL:requestUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
URLRequest.allowsCellularAccess=YES;
[URLRequest setHTTPMethod:#"POST"];
[URLRequest setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[URLRequest setHTTPBody:postData];
WebServiceManager *webserviceManager = [[WebServiceManager alloc] init];// this is your comman class for webServices connections
[webserviceManager sendRequest:URLRequest withOwner:self successAction:#selector(delegateMethod:) failAction:#selector(Error:)];
}
Replace:
NSData *postData = [jsonString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
With:
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:jsonString options:0 error:&error];
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.

How can we add video to a tableview?

In my app i want to display a video in subsequent rows of a tableview. Video's are to be fetched from a JSON service which is coming in a string format. How can we achieve this. Any help will be appreciated.
If you want to use GET for getting response(VIDEO) from server just you can try in following method
//just give your URL instead of my URL
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://api.worldweatheronline.com/free/v1/search.ashx?query=London&num_of_results=3&format=json&key=xkq544hkar4m69qujdgujn7w"]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//You need to check response.Once you get the response copy that and paste in ONLINE JSON VIEWER.If you do this clearly you can get the correct results.
//After that it depends upon the json format whether it is DICTIONARY or ARRAY
//If it is Dictionary
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error: &err];
or
//If it is Array
NSMutableArray *json=[NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:nil];
NSMutableArray *imgvd=[[NSMutableArray alloc]init];
for (int i =0 ; i<json.count; i++)
{
NSString *dd =[[json objectAtIndex:i]objectForKey:#"url"];
NSString *pp = [[json objectAtIndex:i]objectForKey:#"title"];
vedios *myvd = [[vedios alloc]initWithvideo:dd andtitle:pp];
[imgvd addObject:myvd];
}

Proper JSON encoding for HTTP POST request in iOS

Posted a query previously about JSON parsing not working properly. Did more looking into it with a packet sniffer and also with another client that works properly and found out it's a syntax thing, that I still can't seem to solve.
The code in the bottom makes the HTTP request to have the JSON in it as:
{"key":"value"}
And my server is actually looking for a JSON in the following syntax:
key=%22value%22
I tried to write some code that does this manually, but figured there must be something out of the box for iOS, and I don't want to have faults in the future.
I messed around with it for a while trying to find the right code for the job, but couldn't (you can see some code I tried commented out). Can anyone help me?
+ (NSString*)makePostCall:(NSString*)urlSuffix
keys:(NSArray*)keys
objects:(NSArray*)objects{
NSDictionary *params = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
// NSString *dataString = [self getDataStringFromDictionary:params];
// NSData *jsonData = [dataString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params
options:0
error:&error];
// id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
// NSLog(#"%#", jsonObject);
if (!jsonData) {
// should not happen
NSError *error;
NSLog(#"Got an error parsing the parameters: %#", error);
return nil;
} else {
// NSString *jsonRequest = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// NSLog(#"%#", jsonRequest);
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#", urlPrefix, urlSuffix]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
// NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
// [request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: jsonData];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
// TODO: handle error somehow
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return returnString;
}
}

Resources