I'm relatively new to iOS development and my current project requires me to Connect to a website through a Rest API, and use JSON Objects received from the site to populate a Custom UITableViewController which I have implemented. I have been able to download the information and get it to display on the table properly, but this requires me to enter the page which starts the download, then leave the page and enter it again, upon which all of the cells are populated. How can I make my app load this information without leaving the page?
My Custom UITableViewClass contains the following methods:
- (void)viewDidLoad {
[super viewDidLoad];
NSString *chuckFranklinConnection = #"http://chuckfranklinlaw.com/wp-json/posts?type=tribe_events";
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL: [NSURL URLWithString:chuckFranklinConnection]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error){
//Complete Data Handling from Chuckfranklinlaw.com Here
NSString *responseData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSError *e = nil;
jsonArray = [NSJSONSerialization JSONObjectWithData: data options:NSJSONReadingMutableContainers error: &e];
if(!jsonArray) {
NSLog(#"Error parsing JSON: %#", e);
}else {
NSLog(#"Begin Successful Parse Readout -----------");
for(NSDictionary *item in jsonArray) {
NSLog(#"Item: %#", item);
}
}
}]
resume];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<##"reuseIdentifier"#> forIndexPath:indexPath];
// Configure the cell...
EventTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"EventsCell"];
if(cell == nil) {
cell = [[EventTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"EventsCell"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
//Formatting for each Cell Title
cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.textLabel.numberOfLines = 0;
cell.textLabel.text = [[jsonArray objectAtIndex:indexPath.row] objectForKey: #"title"];
//Formatting for each Cell Detail
NSString *startDate = [[jsonArray objectAtIndex:indexPath.row] objectForKey: #"StartDate"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [dateFormatter dateFromString:startDate];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
cell.data = [[jsonArray objectAtIndex:indexPath.row] objectForKey:#"ID"];
cell.detailTextLabel.text = [dateFormatter stringFromDate:date];
//Work On Implementing Image View for App in this section
NSDictionary *imageInfo = [[jsonArray objectAtIndex:indexPath.row] objectForKey:#"featured_image"];
NSDictionary *attachmentMeta = [imageInfo objectForKey:#"attachment_meta"];
NSDictionary *sizes = [attachmentMeta objectForKey:#"sizes"];
NSDictionary *thumbnail = [sizes objectForKey:#"thumbnail"];
NSString *url = [thumbnail objectForKey:#"url"];
NSLog(url);
UIImage* image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];
cell.imageView.image = image;
return cell;
[cell setNeedsDisplay];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"showEventDetail"])
{
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
DetailViewController *detailView = segue.destinationViewController;
NSString *contentString = [[jsonArray objectAtIndex:indexPath.row] objectForKey:#"content"];
//The Following code mutates the HTML Strings recieved from the server into NSStrings for displaying
contentString = [contentString stringByReplacingOccurrencesOfString:#"’" withString:#"\'"];
contentString = [contentString stringByReplacingOccurrencesOfString:#"<p>" withString:#""];
contentString = [contentString stringByReplacingOccurrencesOfString:#"</p>" withString:#"\n"];
detailView.content = contentString;
detailView.title = [[jsonArray objectAtIndex:indexPath.row] objectForKey:#"title"];
NSString *startDate = [[jsonArray objectAtIndex:indexPath.row] objectForKey:#"StartDate"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [dateFormatter dateFromString:startDate];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
detailView.eventTime = [dateFormatter stringFromDate:date];
//Pull Image from web and serve to next page
NSDictionary *imageInfo = [[jsonArray objectAtIndex:indexPath.row] objectForKey:#"featured_image"];
NSDictionary *attachmentMeta = [imageInfo objectForKey:#"attachment_meta"];
NSDictionary *sizes = [attachmentMeta objectForKey:#"sizes"];
NSDictionary *blogFull = [sizes objectForKey:#"blog-full"];
NSString *url = [blogFull objectForKey:#"url"];
detailView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];
}
}
In your completion block: [self.tableview reloadData]. Documentation.
Actually, you will want to create a weak reference to self, then use the weak reference in your completion block.
Related
I am doing a chatting app with JSQmessagecontroller library every thing is working fine but whenever I upload video the page get hang.
I am doing a chatting app with JSQmessagecontroller library every thing is working fine but whenever I upload video the page get hang.
- (id<JSQMessageData>)collectionView:(JSQMessagesCollectionView *)collectionView messageDataForItemAtIndexPath:(NSIndexPath *)indexPath
{
NSString * chat = [[DataArray objectAtIndex:indexPath.row] objectForKey:#"Message"];
NSString * imageurl = [[DataArray objectAtIndex:indexPath.row] objectForKey:#"media"];
if (chat == nil)
{
// NSString *responseString = [[NSString alloc]initWithData:webdata encoding:NSUTF8StringEncoding];
if ([imageurl rangeOfString:#".jpg"].location == NSNotFound) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"Video is Loading....");
image1 =[[UIImageView alloc]init];
MPMoviePlayerController *player1 = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:imageurl]];
[player1 stop];
[self thumbnailImageFromURL:[NSURL URLWithString:imageurl]];
JSQPhotoMediaItem *vitem;
vitem = [[JSQPhotoMediaItem alloc] initWithImage:thumbnailImage];
// NSString * date12=[[DataArray objectAtIndex:indexPath.row] objectForKey:#"date"];
NSString *dateString = [[DataArray objectAtIndex:indexPath.row] objectForKey:#"date"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-YY HH:mm a"];
dateFromString = [[NSDate alloc] init];
dateFromString=[dateFormatter dateFromString:dateString];
messageForRow = [[JSQMessage alloc] initWithSenderId:[[DataArray objectAtIndex:indexPath.row] objectForKey:#"UserId"] senderDisplayName:[[DataArray objectAtIndex:indexPath.row] objectForKey:#"Name"]date:[[DataArray objectAtIndex:indexPath.row] objectForKey:#"date"] media:vitem] ;
// JSQPhotoMediaItem *vitem = [[JSQPhotoMediaItem alloc] initWithImage:thumbnailImage];
});
});
}
else
{
image1 =[[UIImageView alloc]init];
UIImage *im=[[UIImage alloc]init];
[image1 sd_setImageWithURL:[NSURL URLWithString:imageurl]
placeholderImage:nil];
im=image1.image;
JSQPhotoMediaItem *item = [[JSQPhotoMediaItem alloc] initWithImage:im];
NSString *dateString = [[DataArray objectAtIndex:indexPath.row] objectForKey:#"date"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-YY HH:mm a"];
//dateFromString = [[NSDate alloc] init];
dateFromString=[dateFormatter dateFromString:dateString];
messageForRow = [[JSQMessage alloc] initWithSenderId:[[DataArray objectAtIndex:indexPath.row] objectForKey:#"UserId"] senderDisplayName:[[DataArray objectAtIndex:indexPath.row] objectForKey:#"Name"] date:[[DataArray objectAtIndex:indexPath.row] objectForKey:#"date"] media:item] ;
}
}
else
{
messageForRow = [[JSQMessage alloc] initWithSenderId:[[DataArray objectAtIndex:indexPath.row] objectForKey:#"UserId"] senderDisplayName:[[DataArray objectAtIndex:indexPath.row] objectForKey:#"Name"] date:[[DataArray objectAtIndex:indexPath.row] objectForKey:#"date"] text: [[DataArray objectAtIndex:indexPath.row] objectForKey:#"Message"]] ;
}
return messageForRow;
}
i am trying to increment date and year from calendar, but it is incrementing only one value which means (it is incrementing from jan to feb, but it is not incrementing after feb) my requirement is to incrementing upto 12 month and also simultaneously year has to increment. could you please tell me how to resolve this issue this is my code
- (IBAction)right:(id)sender {
[datearray removeAllObjects];
NSCalendar *cal = [NSCalendar currentCalendar];
date = [cal dateByAddingUnit:NSCalendarUnitMonth value:1 toDate:[NSDate date] options:0];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMM YYYY"];
NSString *stringFromDate = [formatter stringFromDate:date];
yar.text=stringFromDate;
NSString *y1=yar.text;
NSArray * arr = [y1 componentsSeparatedByString:#" "];
NSString *m=arr[0];
NSString *yy=arr[1];
spinner = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
spinner.mode = MBProgressHUDModeCustomView;
[spinner setLabelText:#"Loading....."];
[spinner setLabelFont:[UIFont systemFontOfSize:15]];
[spinner show:YES];
//[self.coutweek setText:[NSString stringWithFormat:#"%d",week]];
NSString *urlString = [NSString stringWithFormat:#"http://edvancepreschoolsadminpanel.com/viverobranch/json/json_lunch.php?key=agile89rise98&food=%#&month=%#&year=%#&username=%#",scl,m,yy,temp];
NSLog(#"the url string==%#",urlString);
NSURL *url = [NSURL URLWithString:urlString];
NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSLog(#"the str==%#",jsonString);
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
NSLog(#"%#",results);
luncharray = [[NSMutableArray alloc]init];
NSArray *array=[results objectForKey:#"lunch_menu"];
for (int i=0; i<[array count]; i++) {
NSString *dat =[[array objectAtIndex:i]objectForKey:#"date"];
NSString *mon =[[array objectAtIndex:i]objectForKey:#"month"];
NSString *yea =[[array objectAtIndex:i]objectForKey:#"year"];
NSString *luh =[[array objectAtIndex:i]objectForKey:#"food"];
NSString *tim =[[array objectAtIndex:i]objectForKey:#"time"];
ipadlunch *myimg =[[ipadlunch alloc]initWithdat:dat andmon:mon andyea:yea andlunch:luh andtime:tim];
NSLog(#"%#",myimg);
[luncharray addObject:myimg];
// NSLog(#"the field==%#",videoarray1);
}
This question already has answers here:
How can I sort an NSArray containing NSDictionaries?
(3 answers)
Closed 8 years ago.
I am trying a little project where I get the current location coordinates, then by the current location I find coffee shops nearby and display them in a UITableView. So far I have managed to load the JSON script with the information, parse it into a dictionary, and display it in the UITableView. What I want to do now is try to order the information by 'distance' or by 'name' (alphabetically). How can I do that? Here is some code to show what I have done so far.
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
if (!self.didFindLocation) {
self.didFindLocation = YES;
[self.locationManager stopUpdatingLocation];
}
NSMutableArray *resultArray = [[NSMutableArray alloc] init];
CLLocation *crnLoc = [locations lastObject];
NSString *latitudeString = [NSString stringWithFormat:#"%.10f",crnLoc.coordinate.latitude];
NSString *longitudeString = [NSString stringWithFormat:#"%.10f",crnLoc.coordinate.longitude];
NSString *urlString = [NSString stringWithFormat:#"https://api.foursquare.com/v2/venues/search?client_id=ACAO2JPKM1MXHQJCK45IIFKRFR2ZVL0QASMCBCG5NPJQWF2G&client_secret=YZCKUYJ1WHUV2QICBXUBEILZI1DMPUIDP5SHV043O04FKBHL&ll=%#,%#&query=coffee&v=20140806&m=foursquare", latitudeString, longitudeString];
NSURL *url = [NSURL URLWithString:urlString];
NSData *jsonData = [NSData dataWithContentsOfURL:url];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSDictionary *responseDictionary = [dataDictionary objectForKey:#"response"];
NSDictionary *venueDictionary = [responseDictionary objectForKey:#"venues"];
for (NSDictionary *dict in venueDictionary) {
NSString *name = [dict objectForKey:#"name"];
NSDictionary *locationDictionary = [dict objectForKey:#"location"];
NSString *address = [NSString stringWithFormat: #"%#", [locationDictionary objectForKey:#"address"]];
if (address == nil) {
address = #"No address provided";
}
NSString *distance = [NSString stringWithFormat: #"%#", [locationDictionary objectForKey:#"distance"]];
if (distance == nil) {
distance = #"No coordinates provided";
}
NSLog(#"Name: %# Address: %# distance: %#", name, address, distance);
CoffeeStore *store = [[CoffeeStore alloc] initWithName:name address:address distance:distance];
[resultArray addObject:store];
}
self.storeArray = resultArray;
[self.tableView reloadData]; }
and
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
CoffeeStore *selectedStore = self.storeArray[indexPath.row];
cell.textLabel.text = selectedStore.name;
cell.detailTextLabel.text = selectedStore.distanceString;
return cell;
}
Your resultArray contains an array of CoffeeStore objects, which have a distance given to their init method. You need to sort the array based on distance, before you call reloaddata. Hopefully those objects have a distance property and you can sort by that property, like this:
NSSortDescriptor *distanceDesc = [NSSortDescriptor sortDescriptorWithKey:#"distance" ascending:YES];
self.storeArray = [resultArray sortedArrayUsingDescriptors:#[distanceDesc]];
Very slowly scroll on UITableView images.Help me please.
Did not find the right solution
My code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *const ImageCellId = #"ImageCell";
EXImageCell *cell = [tableView dequeueReusableCellWithIdentifier:ImageCellId];
RSSItem *item = [_data objectAtIndex:indexPath.row];
cell.cellTextLabel.text = item.title;
cell.cellTimeTextLabel.text = [NSDateFormatter localizedStringFromDate:item.pubDate dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterShortStyle];
cell.cellAuthor.text = [NSString stringWithFormat:#"Author: %#", item.author];
NSURL *tutorialsUrl = item.link;
NSData *tutorialsHtmlData = [NSData dataWithContentsOfURL:tutorialsUrl];
TFHpple *tutorialsParser = [TFHpple hppleWithHTMLData:tutorialsHtmlData];
NSString *tutorialsXpathQueryString = #"//div[#class='photo']/img";
NSArray *tutorialsNodes = [tutorialsParser searchWithXPathQuery:tutorialsXpathQueryString];
//NSMutableArray *newTutorials = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in tutorialsNodes) {
tutorial = [[Tutorial alloc] init];
//[newTutorials addObject:tutorial];
//tutorial.title = [[element firstChild] content];
tutorial.url = [element objectForKey:#"src"];
}
NSData *data = [NSData dataWithContentsOfURL : [NSURL URLWithString:tutorial.url]];
UIImage *imageMain = [UIImage imageWithData:data];
[cell.cellImageView setImage:imageMain];
return cell;
}
PS: dispatch_async tried to use, but to no avail
Hi in my application I want to display the Flickr album list in UITableView so i have searched for long time and i have found some solution. I have used the method which given in the solution its not working its giving error like
NSInvalidArgumentException', reason: 'data parameter is nil
The solution link click here
And since I'm trying this for first time I'm not able resolve this issue. This is MY API LINK for Flickr
I have used this code to display the Flickr image Album list in UItableview
{
NSMutableArray *photoURLs;
NSMutableArray *photoSetNames;
NSMutableArray *photoid1;
}
My Flickr API key
#define FlickrAPIKey #"a6a0c7d5efccffc285b0fe5ee1d938e3"
- (void)viewDidLoad
{
[super viewDidLoad];
photoURLs = [[NSMutableArray alloc] init];
photoSetNames = [[NSMutableArray alloc] init];
photoid1 = [[NSMutableArray alloc] init];
[self loadFlickrPhotos];
}
My TableView code
- (void)loadFlickrPhotos
{
NSString *urlString = [NSString stringWithFormat:#"http://api.flickr.com/services/rest/?method=flickr.photosets.getList&api_key=%#&user_id=%#&per_page=10&format=json&nojsoncallback=1", FlickrAPIKey, #"124757153#N04"];
NSURL *url = [NSURL URLWithString:urlString];
NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
NSArray *photosets = [[results objectForKey:#"photosets"] objectForKey:#"photoset"];
for (NSDictionary *photoset in photosets) {
NSString *title = [[photoset objectForKey:#"title"] objectForKey:#"_content"];
[photoSetNames addObject:(title.length > 0 ? title : #"Untitled")];
NSString *photoid = [photoset objectForKey:#"id"];
[photoid1 addObject:photoid];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [photoSetNames count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier =#"Cell";
flickrpoliticalCell *cell =(flickrpoliticalCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[flickrpoliticalCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.tit.text = [photoSetNames objectAtIndex:indexPath.row];
return cell;
}
try this
- (void)loadFlickrPhotos
{
//
NSString *urlString = [NSString stringWithFormat:#"https://www.flickr.com/services/rest/?method=flickr.photosets.getList&api_key=a6a0c7d5efccffc285b0fe5ee1d938e3&format=json&user_id=124757153#N04&per_page=10&nojsoncallback=1",nil];
NSLog(#"the url string==%#",urlString);
NSURL *url = [NSURL URLWithString:urlString];
NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSLog(#"the str==%#",jsonString);
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
NSArray *photosets = [[results objectForKey:#"photosets"] objectForKey:#"photoset"];
for (NSDictionary *photoset in photosets) {
NSString *title = [[photoset objectForKey:#"title"] objectForKey:#"_content"];
NSLog(#"title==%#",title);
[photoSetNames addObject:(title.length > 0 ? title : #"Untitled")];
NSString *primary = [photoset objectForKey:#"primary"];
NSString *server = [photoset objectForKey:#"server"];
NSString *secret = [photoset objectForKey:#"secret"];
NSString *farm = [photoset objectForKey:#"farm"];
NSString *urlstr=[NSString stringWithFormat:#"http://farm%#.staticflickr.com/%#/%#_%#.jpg",farm,server,primary,secret];
NSLog(#"your photo id==%#",urlstr);
[photoids addObject:urlstr];
}
}