I have program which use an API to collect the schedule list of different TV channels, I have maybe 10 TV channels so I don't want to add manually the 10 items in my tabBar controller
I use this code to collect my channels :
- (void)viewDidLoad {
[super viewDidLoad];
NSString *url = [NSString stringWithFormat: #"https://apis.is/tv"];
// Download JSON
NSData *JSONData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
// Parse JSON
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:JSONData //1
options:kNilOptions
error:&error];
NSArray* jsonResult = [json objectForKey:#"channels"];
_channelList = [[NSMutableArray alloc] init];
for (id item in jsonResult) {
TVShow *TVChannel = [[TVShow alloc] init];
TVChannel.channel = [item objectForKey:#"name"];
TVChannel.endpoint = [item objectForKey:#"endpoint"];
[_channelList addObject:TVChannel];
}
}
I wanted to know how with that I can add a tap bar item for each channel
Thanks guys
This code is working fine for me... You can just copy and paste it... :)
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSString *url = [NSString stringWithFormat: #"https://apis.is/tv"];
// Download JSON
NSData *JSONData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
// Parse JSON
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:JSONData //1
options:NSJSONReadingAllowFragments
error:&error];
NSArray* jsonResult = json[#"results"][0][#"channels"];
_channelList = [[NSMutableArray alloc] init];
for (id item in jsonResult) {
TVShow *TVChannel = [[TVShow alloc] init];
TVChannel.channel = item[#"name"];
TVChannel.endpoint = item[#"endpoint"];
[_channelList addObject:TVChannel];
}
NSMutableArray *tabViewControllers = [[NSMutableArray alloc] init];
NSInteger tabTag = 0;
for (TVShow *show in self.channelList) {
ViewController1 *view1 = [[ViewController1 alloc] initWithNibName:#"ViewController1" bundle:[NSBundle mainBundle]];
[tabViewControllers addObject:view1];
view1.mainLabel.text = show.channel;
view1.tabBarItem = [[UITabBarItem alloc] initWithTitle:show.channel
image:nil
tag:tabTag];
tabTag++;
}
UITabBarController *tabBarController = [[UITabBarController alloc] init];
[tabBarController setViewControllers:tabViewControllers];
[self.window setRootViewController: tabBarController];
[self.window makeKeyAndVisible];
return YES;
}
Related
how i can create Dictionary that when i create jsondata with it, json looks like :
"historyStep":[
{
"counter": "50",
"timestamp": "1461674383632"
}
]
I did this :
NSMutableDictionary*jsonDictOth = [[NSMutableDictionary alloc]init];
[jsonDictOth setObject:#(810) forKey:#"counter"];
[jsonDictOth setObject:#"1464957395241.447998" forKey:#"timestamp"];
NSMutableDictionary *jsonDictMain = [[NSMutableDictionary alloc]initWithObjectsAndKeys:jsonDictOth,#"historyStep", nil];
NSError*error;
NSData *data = [NSJSONSerialization dataWithJSONObject:jsonDictMain
options:NSJSONWritingPrettyPrinted
error:&error];
but it looks :
historyStep = {
counter = 810;
timestamp = "1464957395241.447998";
};
You are missing a level: NSDictionary (top level) with NSArray of NSDictionary in the top level key historyStep:
NSMutableDictionary *topLevel = [[NSMutableDictionary alloc] init];
NSArray *historySteps = [[NSMutableArray alloc] init];
//Here you may have a for loop in case there are more steps
NSDictionary *aStep = #{#"counter":#"50", #"timestamp":#"1461674383632"};
[historySteps addObject:aStep]
[topLevel setObject:historySteps forKey#"historyStep"];
NSError*error;
NSData *data = [NSJSONSerialization dataWithJSONObject:topLevel
options:NSJSONWritingPrettyPrinted
error:&error];
NSDictionary *innerDictionary = [[NSDictionary alloc]initWithObjectsAndKeys:#"50", #"counter",#"1461674383632", #"timestamp", nil];
NSArray *array = [[NSArray alloc]initWithObjects:innerDictionary, nil];
NSDictionary *outerDict = [[NSDictionary alloc]initWithObjectsAndKeys:array, #"historyStep", nil];
Use this code it will work perfectly.
Your code should be like,
NSMutableDictionary*jsonDictOth = [[NSMutableDictionary alloc]init];
[jsonDictOth setObject:#(810) forKey:#"counter"];
[jsonDictOth setObject:#"1464957395241.447998" forKey:#"timestamp"];
NSMutableArray *arr = [[NSMutableArray alloc]init];
[arr addObject:jsonDictOth];
NSMutableDictionary *jsonDictMain = [[NSMutableDictionary alloc]initWithObjectsAndKeys:arr,#"historyStep", nil];
NSLog(#"jsonMain is %#",jsonDictMain);
NSError*error;
NSData *data = [NSJSONSerialization dataWithJSONObject:jsonDictMain
options:0
error:&error];
It's output is,
jsonMain is {
historyStep = (
{
counter = 810;
timestamp = "1464957395241.447998";
}
);
}
You just missed one array between
I am trying to store Json data to a mutable array. The JSON data has "city" and main dictionary branch inside a loop , where main branch contains temperature. When I loop through the main, all the previous temperatures are replaced by the later.
Here's the sample code :
object = [[NSMutableArray alloc]init];
NSURL *url = [NSURL URLWithString:#"http://api.openweathermap.org/data/2.5/forecast/city?q=london,uk&APPID="];
//8a7bc4e5d8246122294adb174b708711
NSData *data = [NSData dataWithContentsOfURL:url];
Model *mod = [[Model alloc]init];
NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSDictionary *cityDict = [jsonDict objectForKey:#"city"];
NSString *cityName = [cityDict objectForKey:#"name"];
// NSLog(#"%#",cityName);
NSLog(#"%#",mod.city);
NSMutableArray *arrayOfTemperature = [jsonDict objectForKey:#"list"];
for (NSDictionary *obj in arrayOfTemperature) {
NSDictionary *main = [obj objectForKey:#"main"];
NSString *temp = [main objectForKey:#"temp"];
//NSLog(#"%#",temp);
mod.temp = temp;
[object addObject:mod];
}
You are reusing the same mod instance over and over. You need to create a new one each iteration.
Move the line:
Model *mod = [[Model alloc]init];
to inside the for loop:
NSMutableArray *arrayOfTemperature = [jsonDict objectForKey:#"list"];
for (NSDictionary *obj in arrayOfTemperature) {
Model *mod = [[Model alloc]init];
NSDictionary *main = [obj objectForKey:#"main"];
NSString *temp = [main objectForKey:#"temp"];
//NSLog(#"%#",temp);
mod.temp = temp;
[object addObject:mod];
}
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);
- (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.
I am getting response from web service, the response is based on comma separated URl
NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"ResponseData: %#", str);
And its output is like
ResponseData: http://www.digitalnet.com/androidapi/images/post_images/img_2013-12-09-00-12-46.jpg,http://www.digitalnet.com/androidapi/images/post_images/img_2013-12-09-01-12-32.jpg
I want to pass the response to my Images Gallery Which takes URL like below format
networkImages = [[NSArray alloc] initWithObjects:#"http://www.digitalnet.com/androidapi/images/post_images/img_2013-12-09-00-12-46.jpg",#"http://www.digitalnet.com/androidapi/images/post_images/img_2013-12-09-01-12-32.jpg",nil];
How can I format my response to #"URL",#"URL" so that I can store it into some variable e,g;abc and pass that to
networkImages = [[NSArray alloc] initWithObjects:abc,nil];
NSString has a method componentsSeparatedByString: which does exactly this.
networkImages = [str componentsSeparatedByString:#","];
I think you have two ways :
First way; (that i have already using in my news App)
* You must use JSON result.
* If you want you can use SBJsonParser and SDWebImage
NSError *myError = nil;
NSString *link = [NSString stringWithFormat:#"http://www.myexamplenews.com/mobil-app.php?q=imageList&id=%i",galleryId];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:link] cachePolicy:0 timeoutInterval:5];
NSURLResponse *response=nil;
NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&myError];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:nil];
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
if (myError == nil)
{
NSArray *jsonGalleryDetail = [jsonParser objectWithString:jsonString];
jsonParser = nil;
GalleryDetailView *view = [[GalleryDetailView alloc] initWithFrame:[[UIScreen mainScreen] andImageList: jsonGalleryDetail];
[self.navigationController pushViewController:GalleryDetailView animated:YES];
}
GalleryDetailView.h
#interface GalleryDetailView : UIView
{
}
- (id)initWithFrame:(CGRect)frame andImageList:(NSArray *)myList;
#end
GalleryDetailView.m
#implementation GalleryDetailView
- (id)initWithFrame:(CGRect)frame andImageList:(NSArray *) myList;
{
self = [super initWithFrame:frame];
if (self)
{
//Your code here
for (NSString *str in myList)
{
NSURL *imageURL = [NSURL URLWithString:str];
//This is SDWebImage extension.
UIImage *image = [UIImage setImageWithURL:imageURL placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
}
}
return self;
}
#end
Second way ;
NSArray *arr = [ResponseData componentsSeparatedByString:#","];
GalleryDetailView *view = [[GalleryDetailView alloc] initWithFrame:[[UIScreen mainScreen] andImageList: arr];
[self.navigationController pushViewController:GalleryDetailView animated:YES];
I prefer to use JSON data. It is up to you. I hope this information will be helpful for you.