I am trying to store data from server to NSMutable array to display them as news feeds in table view like shown in this image. Basically like twitter news feeds. What I wanna do is get the data from the server in the NSMutable array and use that array to display in my table view. I don't know if this is the right way to do it. I tried adding statically and it works but I really don't know how to do it dynamically since I'm a newbie to Objective C. Sorry if this question seems really stupid. Thanks in advance!
Parse data using JSON:
dispatch_queue_t jsonParsingQueue = dispatch_queue_create("jsonParsingQueue", NULL);
// execute a task on that queue asynchronously
dispatch_async(jsonParsingQueue, ^{
NSString *urlStr = #"YourURL";
NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url];
[request setHTTPMethod: #"GET"];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseStr = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSData * jsonData = [responseStr dataUsingEncoding:NSUTF8StringEncoding];
NSMutableArray *tempResults = [NSMutableArray alloc];
NSError *jsonParsingError = nil;
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&jsonParsingError];
tempResults = jsonObject[#"posts"]; //Add the json key you would like to get
self.arrayToDisplay = [tempResults copy]; //copy them to your NSMutableArray
// some code on a main thread (delegates, notifications, UI updates...)
dispatch_async(dispatch_get_main_queue(), ^{
[self.myTableView reloadData];
});
});
Related
Good morning,
How can I load a MySQL query result into a UILabel in my iOS app? I need to display the name of the user, the followers and also the profile image. How can I do that?
I have created the storyboard with the UILabels and the UIImageView but now I need to load the data from my MySQL database and I'm a little bit lost.
Thanks in advance.
You can get data with JSON.
NSMutableURLRequest * requestTransfer;
NSString *strUrl = #"www.yoursite.com/Mobile/GetUser";
requestTransfer = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:strUrl]
cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
[requestTransfer setValue:#"gzip" forHTTPHeaderField:#"Accept-Encoding"];
[requestTransfer setHTTPMethod:#"POST"];
NSHTTPURLResponse * response;
NSError* error = nil;
response = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:requestTransfer returningResponse:&response error:&error];
NSDictionary *dicUsers = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
You can use dictionary like that.
NSString* strID = [dictionary objectForKey:#"UserID"];
NSString* strName = [dictionary objectForKey:#"UserName"];
NSString* strLink = [dictionary objectForKey:#"ImageLink"];
yourlabel.text = strName;
I have have some trouble in understanding what is needed to fetch a JSON file with mantle.h from a URL.
Can someone give me an example of how it works?
For example:
-I have a URL www.example.com with a JSONFile as follows:
{
"name": "michael"
}
How could I fetch it?
I use this process for fetching JSON:
NSURL *s = url;//Put your desird url here
NSURLRequest *requestURL = [NSURLRequest requestWithURL:s cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.00];
NSHTTPURLResponse *response;
NSError *error = [[NSError alloc]init];
NSData *apiData = [NSURLConnection sendSynchronousRequest:requestURL returningResponse:&response error:&error];
dictionaryData = [NSJSONSerialization JSONObjectWithData:apiData options:kNilOptions error:&error];
Now the dictionaryData contains your JSON. You can fetch it by:
NSString *name = [dictionaryData valueForKey:#"name"];
And make sure you are making async request. For this put the code within this block:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
//Put the code here
});
Hope this helps.. :)
Call it with following method
[super getRequestDataWithURL:urlString
andRequestName:sometext];
You will get response in the following method if successful
- (void)successWithRequest:(AFHTTPRequestOperation *)operation withRespose:(id)responseObject withRequestName:(NSString *)requestName {
NSString *response = operation.responseString;
id jsonObject = [response objectFromJSONString];
if(![super checkforServerRequestFailureErrorMessage:jsonObject]) {
[self.leaderboardProxyDelegate leaderboardListSuccessful:jsonObject];
}
}
You will get dictionary in jsonObject
I'm really having trouble figuring this out. I'm parsing JSON into an array asynchronously. Running NSLog on the async function prints out an array with multiple objects, which is what I want. But when I run the NSLog on the returned array in the ViewController it only prints out the last object of the array. I then run a count on it and there is, in fact, only 1 object in the array. Why is it only returning an array with one object from an array with multiple objects? Below is my code. Thanks for any input you might have.
Function performed asynchronously
- (NSArray *)locationsFromJSONFile:(NSURL *)url {
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:30.0];
NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSError *error;
NSMutableDictionary *allTeams = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
if( error )
{
NSLog(#"%#", [error localizedDescription]);
}
else {
team = allTeams[#"10"];
for ( NSDictionary *teamArray in team )
{
teams = [NSArray arrayWithObjects: teamArray[#"team"], nil];
}
}
return teams;
}
ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
JSONLoader *jsonLoader = [[JSONLoader alloc] init];
NSURL *url = [[NSBundle mainBundle] URLForResource:#"teams" withExtension:#"json"];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
teams = [jsonLoader locationsFromJSONFile:url];
int i = [teams count];
NSString *string = [NSString stringWithFormat:#"%d", i];
NSLog(#"%#", string);
});
}
You need to add object to the existing array instead of reinitalizing it everytime
teams = [NSArray arrayWithObjects: teamArray[#"team"], nil];
should be
else {
team = allTeams[#"10"];
teams = [NSMutableArray array];
for ( NSDictionary *teamArray in team )
{
[teams addObject:teamArray[#"team"]];
}
Also you are sending synchronous request using this code
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
you should use the sendAsynchronous methods. Synchronous request can be terminated by the OS itself and can lead to some confusion and bugs later on
FIRST EDIT:
I put returnData in JSONObjectWithData:options:error but the error persists.
The problem happens 1 in 10 times, but it's annoying because the application does not work.
2014-02-18 10:26:03.236 finalAbogados[47279:f803] Error en consulta basica: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x686c330 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
im doing an APP on iOS that get a JSON object from a PHP Script.
The script calls data from data base in MS SQL and encode these data in a JSON Object. Then i get the object on iOS and i use NSJSONSerialize for handle data.
The problem is, sometimes I get a null value and sometimes I get the array correctly. The data returned me the script is always the same, expose here:
[{"0":"","NombreOrganismo":"","1":"Judicial","NombreTipoInstancia":"Judicial","2":"(Sin asignar)","Numero":"(Sin asignar)"}]
The code that performs the query and the data in question is:
NSString *myRequestString = [NSString stringWithFormat:#"user=%#&pass=%#&cod_asunto=%#", u_received, p_received, cod_received];
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:#""]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[request setHTTPBody:myRequestData];
NSURLResponse *response;
NSError *error;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *content = [NSString stringWithUTF8String:[returnData bytes]];
NSData *jsondata = [content dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsondata options:kNilOptions error:&jsonError];
NSMutableArray *NombreOrga = [[NSMutableArray alloc] init];
NSMutableArray *NombreInstancia = [[NSMutableArray alloc] init];
NSMutableArray *Numero = [[NSMutableArray alloc] init];
if ([jsonObject isKindOfClass:[NSArray class]]) {
NSLog(#"Its an ARRAY!!.");
NSArray *jsonArray = (NSArray *)jsonObject;
for (id item in jsonArray) {
if ([item isKindOfClass:[NSDictionary class]]) {
NSString *aux = [(NSDictionary*)item objectForKey:#"NombreOrganismo"];
NSString *aux2 = [(NSDictionary*)item objectForKey:#"Numero"];
NSString *aux3 = [(NSDictionary*)item objectForKey:#"NombreTipoInstancia"];
if (aux) {
[NombreOrga addObject:aux];
}
if (aux2) {
[NombreInstancia addObject:aux2];
}
if (aux3) {
[Numero addObject:aux3];
}
} else {
NSLog(#"item %# is not a dictionary",item);
}
}
}
else {
NSLog(#"Its probably a DICTIONARY!.");
}
It's very strange, sometimes NSLog tells me "Its probably a DICTIONARY!" and the value is empty and the app does not work. And sometimes NSLog tells me "Its an ARRAY!" and the application works correctly.
But the data returned by the SCRIPT are always the same!
Thank you very much everyone for your help.
Where JSON_CATEGORY_DATA_URL_STRING is my feed URL, which returns fine as:
[
{
"group":"For Sale",
"code":"SSSS"
},
{
"group":"For Sale",
"category":"Wanted",
"code":"SWNT"
}
]
I cannot seem to get a nice NSDictionary (or NSArray) out of the following code:
+ (NSDictionary *)downloadJSON
{
NSDictionary *json_string;
NSString *dataURL = [NSString stringWithFormat:#"%#", JSON_CATEGORY_DATA_URL_STRING];
NSLog(#"%#",dataURL);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:dataURL]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
json_string = [[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]autorelease];
NSDictionary *json_dict = (NSDictionary *)json_string;
NSLog(#"json_dict\n%#",json_dict);
NSLog(#"json_string\n%#",json_string);
return json_string;
}
I've read many posts on this, but am not getting it.
With IOS5 you can use NSJSONSerialization for serializing the JSON.
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
You can't just cast a string as a dictionary and expect it to parse the JSON. You must use a JSON parsing library to take that string and convert it into a dictionary.
I made a class that makes this task easier. It uses iOS 5's NSJSONSerialization. Clone it from github here.
You need to use JSON parser. here is the edited code
+ (NSDictionary *)downloadJSON
{
NSDictionary *json_string;
NSString *dataURL = [NSString stringWithFormat:#"%#", JSON_CATEGORY_DATA_URL_STRING];
NSLog(#"%#",dataURL);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:dataURL]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
json_string = [[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]autorelease];
//JSONValue is a function that will return the appropriate object like dictionary or array depending on your json string.
NSDictionary *json_dict = [json_string JSONValue];
NSLog(#"json_dict\n%#",json_dict);
NSLog(#"json_string\n%#",json_string);
return json_dict;
}
this should be the code to get the NSDictionary. but you json string is an array so instead use .
+ (NSArray *)downloadJSON
{
NSDictionary *json_string;
NSString *dataURL = [NSString stringWithFormat:#"%#", JSON_CATEGORY_DATA_URL_STRING];
NSLog(#"%#",dataURL);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:dataURL]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
json_string = [[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]autorelease];
NSArray *json_dict = [json_string JSONValue];
NSLog(#"json_dict\n%#",json_dict);
NSLog(#"json_string\n%#",json_string);
return json_dict;
}
Edit:
you need to use JSON.framework to call JSONValue method.
also you need to return json_dict instead of json_string as json_string is of NSString type and not NSDictionary or NSArray.
and dont autorelease it, as it is your class variable
create method to fetchjson data.Pass your url in urlwithstring.
-(void)fetchjsondata
{
NSString *login= [[NSString stringWithFormat:#"your url string"]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"----%#", login);
NSURL *url = [NSURL URLWithString:[login stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//-- Get request and response though URL
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (data) {
dic_property= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(#"%#", dic_property);
NSLog(#"counts=%d",[[dic_property objectForKey:#"Data"]count]);
}
else {
NSLog(#"network error, %#", [error localizedFailureReason]);
}
});
}];
}
call fetchjsonmethod in anywhere.
[NSThread detachNewThreadSelector:#selector(fetchdata) toTarget:self withObject:nil];