I'm trying to parse an image url through JSON in my iPhone application.
My json model is built like this:
{
"picture":"link_to_image.jpg",
"about":"about text here",
"name":"Name"
}
I use this code to parse the itemw in my app:
- (void)fetchedData:(NSData *)responseData
{
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions error:&error];
self.titleLabel.text = [json objectForKey:#"name"];
self.aboutText.text = [json objectForKey:#"about"];
self.profileImage.image = [json objectForKey:#"picture"];
}
And in ViewDidLoad I wrote this:
dispatch_queue_t queue = dispatch_get_global_queue
(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSData *data = [NSData dataWithContentsOfURL:
[NSURL URLWithString:#"link_to_my_json_file.php"]];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
});
I've connected the outlets to the items in my .xib-file and the title and about text are successfully parsed to the label and textview. But the image won't parse. The app keeps crashing when I try this for the image.
Can someone please explain what I'm doing wrong?
Thanks!
As #Hot Licks have mentioned in comments you are putting a NSString pointer into UIImage property. Following method should work.
- (void)fetchedData:(NSData *)responseData
{
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions error:&error];
self.titleLabel.text = [json objectForKey:#"name"];
self.aboutText.text = [json objectForKey:#"about"];
NSURL *URL = [NSURL URLWithString: [json objectForKey:#"picture"]];
dispatch_queue_t queue = dispatch_get_global_queue
(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSData *data = [NSData dataWithContentsOfURL: URL];
self.profileImage.image = [UIImage imageWithData: data];
});
}
Related
Good morning,
I'm trying to develop my first App and I'm using TableView in order to show my entries from a MySQL database and I'm having some trouble when I have to parse the JSON output.
I have already created the connection with my JSON, but now I need to save all the id in a single Array, all the user in another array, etc, etc. As you can see below in my second code, I need to store them in a NSArray. How can I do that?
That's my JSON
[{"id":"15","user":"1","imagen":"http:\/\/farmaventas.es\/images\/farmaventaslogo.png","date":"2014-09-13"}
,{"id":"16","user":"2","imagen":"http:\/\/revistavpc.es\/images\/vpclogo.png","date":"2014-11-11"}]
And that's my TableViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
NSString * urlString = [NSString stringWithFormat:#"http://website.com/service.php"];
NSURL * url = [NSURL URLWithString:urlString];
NSData * data = [NSData dataWithContentsOfURL:url];
NSError * error;
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
// Here I have to store my "user"
self.carMakes = [[NSArray alloc] initWithObjects: nil];
// Here I have to store my "imagen"
self.carModels = [[NSArray alloc] initWithObjects: nil];
}
Thanks in advance.
That's another solution with KVC
NSArray *carMakes = [json valueForKeyPath:#"#unionOfObjects.id"];
NSArray *carModels = [json valueForKeyPath:#"#unionOfObjects.user"];
First of all, you would want to fetch JSON on another thread, so you dont block your main thread with it:
#interface ViewController ()
#end
#implementation ViewController
-(void)viewDidLoad
{
[super viewDidLoad];
[self fetchJson];
}
-(void)fetchJson {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSString * urlString = [NSString stringWithFormat:#"http://website.com/service.php"];
NSURL * url = [NSURL URLWithString:urlString];
NSData * data = [NSData dataWithContentsOfURL:url];
NSError * error;
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
// I advice that you make your carModels mutable array and initialise it here,before start working with json
self.carModels = [[NSMutableArray alloc] init];
#try {
NSError *error;
NSMutableArray* json = [NSJSONSerialization
JSONObjectWithData:theData
options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves
error:&error];
if (error){
NSLog(#"%#",[error localizedDescription]);
}
else{
for(int i=0;i<json.count;i++){
NSDictionary * jsonObject = [json objectAtIndex:i];
NSString* imagen = [jsonObject objectForKey:#"imagen"];
[carModel addObject:imagen];
}
dispatch_async(dispatch_get_main_queue(), ^{
// If you want to do anything after you're done loading json, do it here
}
});
}
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
// Here you have to store my "user"
self.userArray = [[NSMutableArray alloc]init];
for (NSDictionary *userInfo in json){
//get "user" from json
NSString* user = [userInfo objectForKey:#"user"];
//add to array
[userArray addObject:user];
}
You have use NSMutableArray to add object instead.
Since "json" is array of NSDictionary you can get iterate over it and add to arrays like this:
NSArray *json = #[#{#"id":#"15",#"user":#"1",#"imagen":#"http:\/\/farmaventas.es\/images\/farmaventaslogo.png",#"date":#"2014-09-13"},
#{#"id":#"16",#"user":#"2",#"imagen":#"http:\/\/revistavpc.es\/images\/vpclogo.png",#"date":#"2014-11-11"}];
NSArray *carMakes = [NSArray array];
NSArray *carModels = [NSArray array];
for (NSDictionary *dict in json) {
carMakes = [carMakes arrayByAddingObject:dict[#"id"]];
carModels = [carModels arrayByAddingObject:dict[#"user"]];
}
NSLog(#"%#",carMakes);
NSLog(#"%#",carModels);
This question already has an answer here:
Parsing JSON response .
(1 answer)
Closed 8 years ago.
Hai I need to get the id & status from the service for login my code is below. please guide me to get the values.. Thanks in advance..
NSString *Username= txtUsername.text;
NSString *Password=txtPassword.text;
NSString *link = [NSString stringWithFormat:#"http://www.xxx/login.php?user=%#&pass=%#&format=json",Username,Password];
NSURL *url=[NSURL URLWithString:link];
NSData *data=[NSData dataWithContentsOfURL:url];
1st Do the jSon parsing and then get the particular value from the
key .
Before getting any value , we have to understand the tree of jSon.
Here "posts" is an NSArray ,within that one DIctionary "post" is
there ,which again contains another dictionary.
Below is the complete code.
(void)viewDidLoad
{
[super viewDidLoad];
NSString *Username= txtUsername.text;
NSString *Password=txtPassword.text;
NSString *link =
[NSString stringWithFormat:#"http://www.some.com/webservice/login.php?user=%#&pass=%#&format=json",Username,Password];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:
kLatestKivaLoansURL];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
}); }
Then call that selector fetchedData
(void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
if(!error){
NSArray* postArray = [json objectForKey:#“posts”]; //This is an array
if (postArray.count>0) {
NSDictionary *dict = [[postArray objectAtIndex:0] objectForKey:#"post" ];
NSString *id_ = [dict objectForKey:#"id"];
NSString *status_ = [dict objectForKey:#"status"];
}
}
}
Can you post your json string. You can use NSJSONSERIALISATION to convert data (json string ) into NSDictionary. Then use the keys to extract the values. I'm replying through mobile so I can't write the actual code.
Use Below code to parse Json in IOS
NSString *Username= txtUsername.text;
NSString *Password=txtPassword.text;
NSString *link = [NSString stringWithFormat:#"http://www.some.com/_webservice/login.php?user=%#&pass=%#&format=json",Username,Password];
NSURL *url=[NSURL URLWithString:link];
NSMutableURLRequest *req1 = [NSMutableURLRequest requestWithURL:url];
NSURLResponse *response;
NSError *error;
//getting the data
NSData *newData = [NSURLConnection sendSynchronousRequest:req1 returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:newData encoding:NSUTF8StringEncoding];
NSLog(#"basavaraj \n\n\n %# \n\n\n",responseString);
NSData* data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError];
NSString *id=[res objectForKey:#"ID"];
NSString *status=[res objectForKey:#"Status"];
and if u need extra info please go through below link it may help you
Click here for more details
So I've created a service call, and as of now it is working. This is the link to the URL which you must see to be able to help me:
http://jobs.github.com/positions.json?description=python&location=new+york
For some reason, my code here isn't able to retrieve the dictionary objects of the data. It returns SIGABRT.
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *urlString = #"http://jobs.github.com/positions.json?description=python&location=new+york";
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *jobs = json[#" "];
for (NSDictionary *theJob in jobs)
{
NSLog(#"%#", theJob[#"description"]);
}
}
Your JSON is an array of dictionaries. Change
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *jobs = json[#" "];
to
NSArray *jobs = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:#"http://www.xovak.com/json_logo.php"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSDictionary *Logos = [[[json valueForKey:#"logos"]objectAtIndex:0]mutableCopy];
NSMutableArray *img = [[NSMutableArray alloc]init];
for (id item in Logos) {
[img addObject:[Logos objectForKey:#"image_file"]];
NSLog(#"%#",img);
}
}
Are you sure Logos shouldn't be a NSArray? At least, that's what it looks like from your JSON object.
Do this instead:
NSURL *url = [NSURL URLWithString:#"http://www.xovak.com/json_logo.php"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *Logos = [[json valueForKey:#"logos"] mutableCopy];
NSMutableArray *img = [[NSMutableArray alloc]init];
for (NSDictionary *item in Logos) {
[img addObject:[item objectForKey:#"image_file"]];
NSLog(#"%#",img);
}
Another way of getting all imagFile From JSON Response. Please Check it.
NSURL *url = [NSURL URLWithString:#"http://www.xovak.com/json_logo.php"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSMutableArray *img = [[NSMutableArray alloc]init];
NSArray *listOfURL = [[NSArray alloc] init];
NSArray *websiteDetails = (NSArray *) [json objectForKey:#"logos"];
for(int count=0; count<[websiteDetails count]; count++)
{
NSDictionary *websiteInfo = (NSDictionary *) [websiteDetails objectAtIndex:count];
NSString *imagefile = (NSString *) [websiteInfo objectForKey:#"image_file"];
if([imagefile length]>0)
{
NSLog(#"Imagefile URL is: %#",imagefile);
[img addObject:imagefile];
}
}
listOfURL = img;
---------// Add This Method in TableView Cell For Row at IndexPath Method//-----------------
// Logic For Downloading Image From URL and Show in TableviewCell
//get a dispatch queue
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//this will start the image loading in bg
dispatch_async(concurrentQueue, ^{
NSURL *url = [NSURL URLWithString:[listOfURL objectAtIndex:indexPath.row]];
NSData *image = [[NSData alloc] initWithContentsOfURL:url];
//this will set the image when loading is finished
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageview.image = [UIImage imageWithData:image];
});
});
You're putting only one item in Logos. Plus, it should not be NSMutableDictionary but an NSArray.
On the other hand, the items you're looping on in Logos are actually NSDictionarys.
So, your code should now be:
NSArray *Logos = [json valueForKey:#"logos"];
NSMutableArray *img = [[NSMutableArray alloc]init];
for (NSDictionary *item in Logos) {
[img addObject:[item objectForKey:#"image_file"]];
NSLog(#"%#",img);
}
Replace NSDictionary *Logos = [[[json valueForKey:#"logos"]objectAtIndex:0]mutableCopy]; with NSArray *Logos = [[json valueForKey:#"logos"] mutableCopy]; to get all objects.
How can I get single video information using gdata from youtube.
I know I can get a playlist using this code:
However the code does not work to get a single video's data
NSURL *blogURL = [NSURL URLWithString:#"https://gdata.youtube.com/feeds/api/playlists/PL85E8F3CC22BCEDC6?v=2&alt=jsonc"];
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSDictionary *data1 = [dataDictionary objectForKey:#"data"];
NSDictionary *item = [data1 objectForKey:#"items"];
for (NSDictionary *video in item) {
NSDictionary *title = [video objectForKey:#"video"];
NSArray *titleArray = [title objectForKey:#"title"];
NSLog(#"%#",titleArray);
NSString*t = [title objectForKey:#"title"];
NSLog(#"Title:%#", t);
...
}
But I do not know how to get a single video.
Any help will be appreciated...
Thanks...
To get the feed for a single video with v2, you'd replace the URL in the first line with something like this:
https://gdata.youtube.com/feeds/api/videos/tge2BfiIXiE?v=2&alt=jsonc
Where you change the videoID as necessary.
The JSON that is returned with this feed is slightly different, naturally; so rather than creating an NSDictionary object for the items list and then looping over it, you would just do something like this:
NSURL *feedURL = [NSURL URLWithString:#"https://gdata.youtube.com/feeds/api/videos/tge2BfiIXiE?v=2&alt=jsonc"];
NSData *jsonData = [NSData dataWithContentsOfURL:feedURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSDictionary *data1 = [dataDictionary objectForKey:#"data"];
NSString *t = [data1 objectForKey:#"title"];
NSLog(#"Title:%#", t);
NSDictionary *thumbs = [data1 objectForKey:#"thumbnail"];
NSURL *standardThumb = [thumbs objectForKey:#"sqDefault"];
NSURL *hdThumb = [thumbs objectForKey:#"hqDefault"];
code edited to reflect question in comment