Detail view Controller with Parsing the web-service(JSON) - ios

In my App, I have a list of news to be shown and I'm using custom tableview which has a Title, Thumbnail image and more button. On Tapping more button, it will take to the detail view which has description. I've parsed the JSON response for listing the feed in page. But I'm strucked with the detail page. Following is my code:
.m file
#interface NewsViewController ()
#property (nonatomic , retain) NSMutableArray *mArray;
#property (nonatomic , retain) NSDictionary *nDic;
#end
#implementation NewsViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:#"http://almithaq.mawaqaademo11.com/API.svc/getNews" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.nDic = (NSDictionary *)responseObject;
self.mArray = self.nDic[#"News"];
[self.mTab reloadData];
NSLog(#"response dateJSON: %#", self.mArray);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
#pragma mark - TableConfiguration
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.mArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *Identifier = #"MyIdentifier";
NewsCell *cell12 = (NewsCell *)[tableView dequeueReusableCellWithIdentifier:Identifier];
if (cell12 == nil) {
NSArray *nib = [[NSBundle mainBundle]loadNibNamed:#"NewsCell" owner:self options:nil];
cell12 = [nib objectAtIndex:0];
}
cell12.newsDescription.text = [[self.mArray objectAtIndex:indexPath.row] objectForKey:#"Description"];
cell12.newsTitle.text = [[self.mArray objectAtIndex:indexPath.row] objectForKey:#"Title"];
cell12.newsThumbnail.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://%#",[[self.mArray objectAtIndex:indexPath.row] objectForKey:#"NewsImage"]]]]];
cell12.newsMore.tag = indexPath.row;
[cell12.newsMore addTarget:self action:#selector(NewsClicked:) forControlEvents:UIControlEventTouchUpInside];
return cell12;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 220;
}
-(void)backButtonClicked:(UIButton*)sender
{
if (sender.tag <= 25)
{
[self.navigationController popViewControllerAnimated:YES];
}
}
-(void)NewsClicked:(UIButton *)sender
{
if (sender.tag <= 25) {
NewsDetails *view1 = [[NewsDetails alloc]initWithNibName:#"NewsDetails" bundle:nil];
[self.navigationController pushViewController:view1 animated:YES];
}}
Advice, thanks in advance.

Related

Use Search Bar using dynamically generated array

I want to use SearchBar where the elements are generated dynamically with the help of service. Like, if I will pass "i" as parameter, service will fetch all the elements which includes "i" as initial characters. I cannot retrieve the logic as how to implement that in code.
Below is the service am using to get data. But I don't know how to implement Search bar using it.
NSURL * url=[NSURL URLWithString:#"http://dealnxt.com/api/search?searchkey=i"];
NSData * data=[NSData dataWithContentsOfURL:url];
NSError * error;
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"Array is:%#",array);
Below i the code I tried :
.h file
#import <UIKit/UIKit.h>
#interface SearchViewController : UIViewController<UISearchDisplayDelegate,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,UISearchResultsUpdating,UISearchControllerDelegate,UITextFieldDelegate>
{
NSMutableArray *contentList;
NSMutableArray *filteredContentList;
BOOL isSearching;
}
#property (strong, nonatomic) IBOutlet UIView *SearchView;
#property (strong, nonatomic) IBOutlet UISearchBar *SearchBar;
#property (strong, nonatomic) IBOutlet UISearchDisplayController *Search;
#property (strong, nonatomic) IBOutlet UITableView *Content;
#end
.m file
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (isSearching) {
return [filteredContentList count];
}
else {
return [contentList count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (isSearching) {
cell.textLabel.text = [filteredContentList objectAtIndex:indexPath.row];
}
else {
cell.textLabel.text = [[contentList objectAtIndex:indexPath.row] valueForKey:#"shortdescription"];
}
return cell;
}
- (void)searchTableList {
NSString *searchString = _SearchBar.text;
NSString *UrlString =[NSString stringWithFormat:#"http://dealnxt.com/api/search?searchkey=%#",searchString];
NSMutableURLRequest *Request = [[NSMutableURLRequest alloc] init];
[Request setURL:[NSURL URLWithString:UrlString]];
[Request setHTTPMethod:#"GET"];
NSData *ReturnData = [NSURLConnection sendSynchronousRequest:Request returningResponse:nil error:nil];
NSString *str=[[NSString alloc]initWithData:ReturnData encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
contentList=[jsonDict objectForKey:#"ProductDescriptionModel"];
[filteredContentList addObject:[[contentList firstObject] valueForKey:#"shortdescription"]];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
isSearching = YES;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
NSLog(#"Text change - %d",isSearching);
//Remove all objects first.
[filteredContentList removeAllObjects];
if([searchText length] != 0) {
isSearching = YES;
[self searchTableList];
}
else {
isSearching = NO;
}
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
NSLog(#"Cancel clicked");
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
NSLog(#"Search Clicked");
[self searchTableList];
}
Here is the solution :
.h file
#import
#interface SearchViewController : UIViewController<UISearchDisplayDelegate,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,UISearchResultsUpdating,UISearchControllerDelegate,UITextFieldDelegate>
{
NSMutableArray *contentList;
NSMutableArray *filteredContentList;
BOOL isSearching;
}
#property (strong, nonatomic) IBOutlet UIView *SearchView;
#property (strong, nonatomic) IBOutlet UISearchBar *SearchBar;
#property (strong, nonatomic) IBOutlet UISearchDisplayController *Search;
#property (strong, nonatomic) IBOutlet UITableView *Content;
#end
.m file
#import "SearchViewController.h"
#import "UIColor+HexString.h"
#interface SearchViewController ()
#end
#implementation SearchViewController
- (void)viewDidLoad {
[super viewDidLoad];
_SearchView.backgroundColor=[UIColor colorWithHexString:#"#5130F7"];
_SearchBar.barTintColor=[UIColor colorWithHexString:#"#5130F7"];
_SearchBar.layer.borderWidth = 1;
_SearchBar.layer.borderColor = [UIColor colorWithHexString:#"#5130F7"].CGColor;
_Content.delegate=self;
_Content.dataSource=self;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (isSearching) {
return [filteredContentList count];
}
else {
return [contentList count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (isSearching) {
cell.textLabel.text = [filteredContentList objectAtIndex:indexPath.row];
}
else {
cell.textLabel.text = [[contentList objectAtIndex:indexPath.row] valueForKey:#"shortdescription"];
}
return cell;
}
- (void)searchTableList {
NSString *searchString = _SearchBar.text;
NSString *UrlString =[NSString stringWithFormat:#"http://abc.in/key?key=%#",searchString];
NSMutableURLRequest *Request = [[NSMutableURLRequest alloc] init];
[Request setURL:[NSURL URLWithString:UrlString]];
[Request setHTTPMethod:#"GET"];
NSData *ReturnData = [NSURLConnection sendSynchronousRequest:Request returningResponse:nil error:nil];
NSString *str=[[NSString alloc]initWithData:ReturnData encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
contentList=[jsonDict objectForKey:#"ProductDescriptionModel"];
filteredContentList =[contentList valueForKey:#"shortdescription"];
NSLog(#"filter:%#",filteredContentList);
[_Content reloadData];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
isSearching = YES;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
NSLog(#"Text change - %d",isSearching);
//[filteredContentList removeAllObjects];
if([searchText length] != 0) {
isSearching = YES;
[self searchTableList];
}
else {
isSearching = NO;
}
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
NSLog(#"Cancel clicked");
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
NSLog(#"Search Clicked");
[self searchTableList];
}
#end
Easy way to search anything from dynamic array
your controller.m
{
NSMutableArray *contacts;
NSMutableArray *combinearray;
NSString *searchTextString;
NSMutableArray *searchArray;
BOOL isFilter;
}
- (void)viewDidLoad {
[super viewDidLoad];
txtSearchBar.backgroundColor=Clear;
txtSearchBar.layer.cornerRadius=2;
txtSearchBar.clipsToBounds=YES;
txtSearchBar.delegate =self;
txtSearchBar.layer.borderColor=Black.CGColor;
txtSearchBar.layer.borderWidth=2.0f;
[txtSearchBar addTarget:self action:#selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
txtSearchBar.layer.sublayerTransform = CATransform3DMakeTranslation(20, 0, 0);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
if(isFilter)
{
return [searchArray count];
}
else
return arrCardsName.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(isFilter)
{
yourDictionary = [searchArray objectAtIndex:indexPath.row];
}
else
{
yourDictionary = [yourArray objectAtIndex:indexPath.row];
}
return cell;
}
-(void)textFieldDidChange:(UITextField*)textField
{
searchTextString = textField.text;
[self updateSearchArray:searchTextString];
}
-(void)updateSearchArray:(NSString *)searchText
{
if (searchText.length > 0)
{
isFilter=YES;
searchArray = [NSMutableArray array];
searchText = [NSString stringWithFormat:#"%#",searchText];
for ( NSDictionary* item in yourArray )
{
//NSLog(#"contacts ----->%#",[item objectForKey:#"city"]);
if ([[[item objectForKey:#"city"] lowercaseString] rangeOfString:[searchText lowercaseString]].location != NSNotFound)//object for key #"do whatever you want to search"
{
[searchArray addObject:item];
}
}
}
if (!searchText || searchText.length == 0)
{
isFilter=NO;
searchArray = [yourArray mutableCopy];
}
else
{
if ([searchArray count] == 0)
{
NSLog(#"No data From Search");
}
}
// NSLog(#"search array ====>%#",searchArray);
[tbleView reloadData];
}

pass web link from UItableViewCell to UIWebView using parse backend

I have been stuck on this all day and I'm looking for some help. I am making an app where someone can type in a web address that web address will be stored in a table view. When the user taps on that cell it will take them to the web view where they can view that site. I am using parse as my backend to store the user input. ( I am not using PFQueryTableView)
Here is my code for the tableViewController:
interface MenuTableViewController : UITableViewController
#property(strong, nonatomic) NSMutableArray *referralArray;
#property (strong, nonatomic) PFObject *selectLink;
#property (nonatomic, strong) NSArray *webInput;
#property (nonatomic, strong) UIRefreshControl *refreshControl;
#end
#interface MenuTableViewController ()
#end
#implementation MenuTableViewController
#synthesize referralArray;
- (void)viewDidLoad
{
[super viewDidLoad];
PFUser *currentUser = [PFUser currentUser];
if (currentUser) {
NSLog(#"Current user: %#", currentUser.username);
}
else {
[self performSegueWithIdentifier:#"showLogin" sender:self];
}
//refresh inbox
self.refreshControl = [[UIRefreshControl alloc] init];
[self.refreshControl addTarget:self action:#selector(retrieveMessages) forControlEvents:UIControlEventValueChanged];
//swipe to delete
self.tableView.allowsMultipleSelectionDuringEditing = NO;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.navigationController.navigationBar setHidden:NO];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.webInput count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"refCell"forIndexPath:indexPath];
PFObject *web = [self.webInput objectAtIndex:indexPath.row];
cell.textLabel.text = [web objectForKey:#"RefLink"];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
self.selectLink = [self.webInput objectAtIndex:indexPath.row];
//NSString *fileType = [self.selectLink objectForKey:#"RefLink"];
//[self performSegueWithIdentifier:#"webSegue" sender:self];
NSDictionary *dict = [self.webInput objectAtIndex:indexPath.section];
NSString *link=[dict valueForKey:#"link"];
//Create a URL object.
NSURL *url = [NSURL URLWithString:link];
UINavigationController *nav = [self.storyboard instantiateViewControllerWithIdentifier:#"WebView"];
WebViewController *web = (WebViewController *)nav.topViewController;
web.webLink =url;
}
//swipe to delete
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return YES if you want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
//try this
PFObject *object = [self.webInput objectAtIndex:indexPath.row];
[object deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
[self refreshControl];
[self.tableView reloadData];
}];
}
}
#pragma mark - Helper methods
- (void)retrieveMessages {
PFQuery *query = [PFQuery queryWithClassName:#"Referrals"];
//[query whereKey:#"recipientIds" equalTo:[[PFUser currentUser] objectId]];
//run the query here for messages
[query orderByDescending:#"createdAt"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (error) {
NSLog(#"Error: %# %#", error, [error userInfo]);
}
else {
// We found messages!
self.webInput = objects;
[self.tableView reloadData];
NSLog(#"Retrieved %lu messages", (unsigned long)[self.webInput count]);
}
if ([self.refreshControl isRefreshing]) {
[self.refreshControl endRefreshing];
}
}];
}
#pragma mark - LogOut
- (IBAction)logout:(id)sender {
[PFUser logOut];
[self performSegueWithIdentifier:#"showLogin" sender:self];
}
#pragma mark - Segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"showLogin"]) {
[segue.destinationViewController setHidesBottomBarWhenPushed:YES];
}
else if ([segue.identifier isEqualToString:#"webSegue"]) {
[segue.destinationViewController setHidesBottomBarWhenPushed:YES];
WebViewController *webView = (WebViewController *)segue.destinationViewController;
webView.webAddress = self.selectLink;
}
}
#end
If Someone could help me out I would greatly appreciate it!

Loading plist from URL instead of file

I am currently trying to load a plist file from a URL. I'm not sure if the way I have my code set up is causing it to crash or if I'm doing something wrong.
.m file
#import "deptTableViewController.h"
#interface deptTableViewController ()
#property (nonatomic, copy) NSDictionary *names;
#property (nonatomic, copy) NSArray *keys;
#property (nonatomic, strong) NSMutableArray *filterednames;
#property (nonatomic, strong) UISearchDisplayController *searchController;
#end
#implementation deptTableViewController
#synthesize names, keys, filterednames, searchController, searchNames;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
UITableView *tableview = (id) [self.view viewWithTag:1];
[tableview registerClass:[UITableViewCell class] forCellReuseIdentifier:#"Cell"];
filterednames = [[NSMutableArray alloc]init];
searchController = [[UISearchDisplayController alloc]init];
searchController.searchResultsDataSource = self;
// This will get the plist into data format
NSData *dataReturn = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://morphinggamers.ca/staff.plist"]];
NSString *path = [[NSBundle mainBundle]pathForResource:#"staff" ofType:#"plist"];
names = [NSDictionary dictionaryWithContentsOfFile:path];
keys = [[names allKeys]sortedArrayUsingSelector:#selector(compare:)];
keys = [NSKeyedUnarchiver unarchiveObjectWithData:dataReturn];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (tableView.tag == 1) {
return [keys count];
}
else{
return 1;
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if (tableView.tag == 1) {
NSString *key = keys[section];
NSArray *keyValues = names[key];
return [keyValues count];
}
else {
return [filterednames count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
if (tableView.tag == 1) {
names = keys[indexPath.row];
NSString *teacherNames = names[#"teacherNames"];
cell.textLabel.text = teacherNames;
}
else{
cell.textLabel.text = filterednames [indexPath.row];
}
return cell;
}
-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
if (tableView.tag == 1) {
return keys[section];
}
else{
return nil;
}
}
#pragma mark - Search Display And Delegate Methods
-(void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView {
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"Cell"];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
[filterednames removeAllObjects];
if (searchString.length > 0) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains [search] %#", self.searchNames.text];
for (NSString *key in keys) {
NSArray *matches = [names[key]filteredArrayUsingPredicate:predicate];
[filterednames addObjectsFromArray:matches];
}
}
return YES;
}
#end
You can only use initwithcontentsofurl using local files (files on your device already) This URL is on a server so you need to use a network request to fetch the data from the server.
NSURLRequest *request = [NSURLRequest requestWithURL:#"http://morphinggamers.ca/staff.plist"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSDictionary *names = [NSPropertyListSerialization propertyListFromData:data mutabilityOption:0 format:0 errorDescription:nil];
keys = [[names allKeys]sortedArrayUsingSelector:#selector(compare:)];
keys = [NSKeyedUnarchiver unarchiveObjectWithData:dataReturn];
//might want to reload the tableview
[self.tableview reloadData]
}];

self.objects is empty in PFQueryTableViewController

I am trying to display data in different sections using PFQueryTableViewController. The code suggested in https://parse.com/questions/using-pfquerytableviewcontroller-for-uitableview-sections seemed to work, but I couldn't get the data to load on self.objects. Here is my code:
#import "AKAdminViewStudentsViewController.h"
#interface AKAdminViewStudentsViewController ()
#property (strong, nonatomic) NSMutableDictionary *sections;
#property (strong, nonatomic) NSMutableDictionary *sectionToClassMap;
#end
#implementation AKAdminViewStudentsViewController
#synthesize sections = _sections;
#synthesize sectionToClassMap = _sectionToClassMap;
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
self.parseClassName = #"Students";
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[self.tableView reloadData];
NSLog(#"sections found: %#", self.sections); // returns null
NSLog(#"sectionToClassMap: %#", self.sectionToClassMap); // returns null
NSLog(#"objects in table: %#", self.objects); // this found to be empty
}
...
#pragma mark - Tableview methods
- (PFQuery *)queryForTable
{
PFQuery *queryStudents = [PFQuery queryWithClassName:#"Students"];
[queryStudents whereKey:#"student_admin" equalTo:[PFUser currentUser]];
if ([self.objects count]==0) {
queryStudents.cachePolicy = kPFCachePolicyCacheThenNetwork;
}
[queryStudents orderByAscending:#"class_name"];
return queryStudents;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return self.sections.allKeys.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSString *className = [self classForSection:section];
NSArray *rowIndicesInSection = [self.sections objectForKey:className];
return rowIndicesInSection.count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSString *className = [self classForSection:section];
return className;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
{
static NSString *CellIdentifier = #"Students";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell==nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// Configure cell
cell.textLabel.text = [NSString stringWithFormat:#"%#", object[#"full_name"]];
NSDateFormatter *formatDate = [[NSDateFormatter alloc] init];
[formatDate setDateStyle:NSDateFormatterShortStyle];
cell.detailTextLabel.text = [NSString stringWithFormat:#"%#", [formatDate stringFromDate:object[#"createdAt"]]];
return cell;
}
#pragma mark - Helper methods
- (void)objectsDidLoad:(NSError *)error
{
[super objectsDidLoad:error];
// Clear data before loading
[self.sections removeAllObjects];
[self.sectionToClassMap removeAllObjects];
NSInteger section = 0;
NSInteger rowIndex = 0;
for (PFObject *object in self.objects) {
NSString *className = [object objectForKey:#"class_name"];
NSMutableArray *objectsInSection = [self.sections objectForKey:className];
if (!objectsInSection) {
objectsInSection = [NSMutableArray array];
// Create new section for new class found
[self.sectionToClassMap setObject:className forKey:[NSNumber numberWithInt:section++]];
}
[objectsInSection addObject:[NSNumber numberWithInt:rowIndex++]];
[self.sections setObject:objectsInSection forKey:className];
}
}
- (PFObject *)objectAtIndexPath:(NSIndexPath *)indexPath
{
NSString *className = [self classForSection:indexPath.section];
NSArray *rowIndicesInSection = [self.sections objectForKey:className];
NSNumber *rowIndex = [rowIndicesInSection objectAtIndex:indexPath.row];
return [self.objects objectAtIndex:[rowIndex intValue]];
}
- (NSString *)classForSection:(NSInteger)section
{
return [self.sectionToClassMap objectForKey:[NSNumber numberWithInt:section]];
}
#end
When I look at the NSLog data, self.objects is empty. I know this is the reason why data isn't displayed, and would like some advice to sort this out please! Thanks.

UITableView suddenly not retrieving data from Parse

This was working fine yesterday and without touching anything it stopped working today. When I run the query to allocate my 'filterEvents' array, 'objects' in the block is empty. Anyone know what's going on?
#import "FilterViewController.h"
#interface FilterViewController ()
#end
#implementation FilterViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.filterTable.dataSource = self;
self.filterTable.delegate = self;
[self performSelector:#selector(retrieveFilteredEvents)];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.filterEvents count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"filterTableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
NSDictionary *tempDict = [self.filterEvents objectAtIndex:indexPath.row];
self.eventTitle = [tempDict objectForKey:#"eventType"];
cell.textLabel.text = self.eventTitle;
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *tempDict = [self.filterEvents objectAtIndex:indexPath.row];
NSString *string = [tempDict objectForKey:#"eventType"];
[self.delegate setFilter:string];
[self dismissViewControllerAnimated:YES completion:nil];
[[NSNotificationCenter defaultCenter] postNotificationName:#"updateParent" object:nil];
}
#pragma mark - Helper Methods
- (IBAction)done:(id)sender
{
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)retrieveFilteredEvents
{
PFQuery *retrieveEvents = [PFQuery queryWithClassName:#"eventTypes"];
[retrieveEvents orderByAscending:#"eventOrder"];
[retrieveEvents findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
self.filterEvents = [[NSArray alloc] initWithArray:objects];
NSLog(#"%#", self.filterEvents);
}
[self.filterTable reloadData];
}];
}
#end

Resources