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];
}
Related
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....
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 :)
I am trying to access a url which is returning some data which has Chinese characters. It returns following response in browser:
{"news":"新聞發佈"}
But when I am trying to read it in my Objective C code I am getting nil in nsdata. Following is my Objective C code:
NSString *final_url = [NSString stringWithFormat:#"http://xx.xxx.xx.xx:xxxx/iph1/NewsAction.do?service=NEWSNOTIF&lang=2&uid=xxxxxxx"];
final_url = [final_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:final_url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
NSURLResponse *response;
NSError *error = [[NSError alloc] init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *strResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *objectData = [strResponse dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&error];
NSLog(#"json %#",json);
Edit
For testing server guy is sending following data:
String testJson ="新聞發佈";
I there is no error. And data is nil. Then the response form the server itself is not being received. First try by asking the server to send normal string. I think the reason data is nil is not to do with the string encoding here. I suspect the response itself isn't received.
I meet a problem to parse a jSON, I've a jSON like that :
{
"id": 0,
"message": "ok"
}
I tried several things to try to get the value of "id", and "message", but I've always an error..
How can I do to pick the value of "id", and "message" please ?
(I get the result of my JSON in a NSMutableArray)
EDIT :
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSError *jsonParsingError = nil;
NSMutableDictionary *publicTimeline = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];
NSMutableArray *sortedArray = [NSMutableArray arrayWithArray:publicTimeline.allKeys];
[sortedArray sortUsingSelector:#selector(localizedStandardCompare:)];
return sortedArray;
Your JSON string represents a dictionary. So you have to use NSDictionary instead of NSArray.
EDIT I
// convert dictionary into JSON
NSDictionary *fromDict = #{#"id": #(0), #"message": #"ok"};
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:fromDict options:0 error:nil];
// convert data (like you get from an API request) to dictionary
NSDictionary *toDict = [NSJSONSerialization JSONObjectWithData:JSONData options:0 error:nil];
Try this,
Parse the JSON response to NSDictionary
NSDictionary * responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSString *message = [responseDictionary valueForKey:#"message"];
I think its helpful to you (In this response you get first dictionary and dictionary contains two key.so )
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSError *jsonParsingError = nil;
NSDictionary *publicTimeline = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];
NSString *message = [publicTimeline valueForKey:#"message"];
I Think it useful link for you. json parser
On iOS 5, how can I query a web service using a JSON object?
I've tried a bunch of different approaches and can't get it to work. It appears that the AFNetworking or RestKit frameworks are the easiest routes, but I don't have experience with either. I'm also new to iOS development.
Here's an example query that works:
https://site.com/gis?QUERY={"ARGUMENTS":{"TO":{"OBJECT_TYPE":"BUILDING","OBJECT_ID":"1","TYPE":"IDENTIFIER"},"FROM":{"OBJECT_TYPE":"BUILDING","OBJECT_ID":"2","TYPE":"IDENTIFIER"},"PATHTYPES":["SIDEWALK"},"QUERYTYPE":"FINDPATH"}
Create a url request, see example below. This posts json data. In your case, your using a GET http method, so you shouldn't need to post the json data, you can simply include it in the url. Note that some of my variable declarations are not shown.
NSArray *keys = [NSArray arrayWithObjects:#"longitude", #"latitude", nil];
NSArray *objects = [NSArray arrayWithObjects:longitude, latitude, nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
if([NSJSONSerialization isValidJSONObject:jsonDictionary])
{
__jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:nil];
__jsonString = [[NSString alloc]initWithData:__jsonData encoding:NSUTF8StringEncoding];
}
// Be sure to properly escape your url string.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:#"https://site.com...etc"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: __jsonData];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [__jsonData length]] forHTTPHeaderField:#"Content-Length"];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned) {
// Handle error.
}
else
{
NSError *jsonParsingError = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError];
}