How to put JSON element into UITextView? - mysql

I have a MySQL database and a PHP script that work perfectly. However, I was wondering how I could get this data from JSON format to a UITextView. I also have a table being populated with 2 other JSON elements. Thanks!
TableInfo.h
#import <Foundation/Foundation.h>
#interface TableInfo : NSObject
#property (nonatomic, strong) NSString *Title;
#property (nonatomic, strong) NSString *SubTitle;
#property (nonatomic, strong) NSString *Description;
#end
HomeModel.h
#import <Foundation/Foundation.h>
#protocol HomeModelProtocol <NSObject>
- (void)itemsDownloaded:(NSArray *)items;
#end
#interface HomeModel : NSObject <NSURLConnectionDataDelegate>
#property (nonatomic, weak) id<HomeModelProtocol> delegate;
- (void)downloadItems;
#end
HomeModel.m
#import "HomeModel.h"
#import "TableInfo.h"
#interface HomeModel()
{
NSMutableData *_downloadedData;
}
#end
#implementation HomeModel
- (void)downloadItems
{
// Download the json file
NSURL *jsonFileUrl = [NSURL URLWithString:#"http://gandouhaiti.ueuo.com/service.php"];
NSLog(#"Donwload the JSON file");
// Create the request
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:jsonFileUrl];
NSLog(#"Create the request");
// Create the NSURLConnection
[NSURLConnection connectionWithRequest:urlRequest delegate:self];
NSLog(#"Create the NSURLConnection");
}
#pragma mark NSURLConnectionDataProtocol Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"Inititalize the data object");
// Initialize the data object
_downloadedData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the newly downloaded data
[_downloadedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// Create an array to store the locations
NSMutableArray *_locations = [[NSMutableArray alloc] init];
// Parse the JSON that came in
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:_downloadedData options:NSJSONReadingAllowFragments error:&error];
// Loop through Json objects, create question objects and add them to our questions array
for (int i = 0; i < jsonArray.count; i++)
{
NSDictionary *jsonElement = jsonArray[i];
// Create a new location object and set its props to JsonElement properties
TableInfo *newdata = [[TableInfo alloc] init];
newdata.Title = jsonElement[#"Title"];
newdata.SubTitle = jsonElement[#"SubTitle"];
newdata.description = jsonElement[#"Description"];
// Add this question to the locations array
[_locations addObject:newdata];
}
// Ready to notify delegate that data is ready and pass back items
if (self.delegate)
{
[self.delegate itemsDownloaded:_locations];
}
}
#end

If you wan to display the JSON in UITextView in storyboard, kindly try the following:
#implementation ViewController
NSString * JSON;
-(void) viewDidLoad
{
JSON = //get data from remote;
NSString *stringForTextView = #"";
NSData *data = [JSON dataUsingEncoding:NSUTF8StringEncoding];
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
if([array count] >0)
{
for(NSDictionary *d in array)
{
stringForTextView = [NSString stringWithFormat:#"Title:%#\nSubTitle:%#\nDescription:%#\n", [d valueForKey:#"Title"], [d valueForKey:#"SubTitle"], [d valueForKey:#"Description"]];
}
}
_textView.text = stringForTextView;
}
#end

Related

AFNetworking, NSURLSession and json Response (Ronak Sankhala)

I am trying to get json response from a web-service api. I want to extract product data from the json. I also want to implement this using AFNetworking and i also trying to get response using NSURLSession and its completely working.
viewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
#property (weak, nonatomic) IBOutlet UITableView *tblTableView;
- (IBAction)btnClickedPostData:(id)sender;
#end
viewController.m
#import "ViewController.h"
#import "AFNetworking.h"
#import "ResponseTableViewCell.h"
#interface ViewController ()
{
NSMutableDictionary *dictArray;
NSMutableArray *dataArray;
}
#end
#implementation ViewController
static NSString *CellIdentifier = #"cell";
- (void)viewDidLoad {
[super viewDidLoad];
[self.tblTableView registerNib:[UINib nibWithNibName:#"ResponseTableViewCell" bundle:nil] forCellReuseIdentifier:#"ResponseTableViewCell"];
[self connectionString];
}
-(void)connectionString
{
//NSURL *URL = [NSURL URLWithString:#"Your URL"];
NSURLSession *session = [NSURLSession sharedSession]; // its working
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:#"YOUR URL"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSMutableDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#", jsonResponse);
dataArray = [jsonResponse objectForKey:#"objEventcategoryList"];
self.tblTableView.dataSource = self;
self.tblTableView.delegate = self;
[self.tblTableView reloadData];
NSLog(#"JSON: %#", dataArray);
}];
[dataTask resume];
// AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; // its working
// [manager GET:URL.absoluteString parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
//
// NSMutableDictionary *jsonResponse = (NSMutableDictionary *)responseObject;
// dataArray = [jsonResponse objectForKey:#"objEventcategoryList"];
//
// self.tblTableView.dataSource = self;
// self.tblTableView.delegate = self;
//
// [self.tblTableView reloadData];
//
// NSLog(#"TableView: %#", _tblTableView);
//
//
// NSLog(#"JSON: %#", dataArray);
// } failure:^(NSURLSessionTask *operation, NSError *error) {
// NSLog(#"Error: %#", error);
// }];
}
#pragma marrk
#pragma marrk - TableView DataSource and Deleget
#pragma marrk
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [dataArray count];// its not working
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
ResponseTableViewCell *cell = (ResponseTableViewCell *)[tableView dequeueReusableCellWithIdentifier:#"ResponseTableViewCell"];
dictArray = [dataArray objectAtIndex:indexPath.row];
//cell.lblCatID.text = [dictArray objrct:#""];
cell.lblCatID.text = [NSString stringWithFormat:#"%#", [dictArray valueForKey:#"EventCategoryId"]];
cell.lblEventName.text = [NSString stringWithFormat:#"%#", [dictArray valueForKey:#"EventCategoryName"]];
cell.lblCreateDate.text = [NSString stringWithFormat:#"%#", [dictArray valueForKey:#"CreatedDate"]];
cell.layoutMargins = UIEdgeInsetsZero;
return cell;
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
if ([tableView respondsToSelector:#selector(setSeparatorInset:)])
{
[tableView setSeparatorInset:UIEdgeInsetsZero];
}
if ([tableView respondsToSelector:#selector(setLayoutMargins:)])
{
[tableView setLayoutMargins:UIEdgeInsetsZero];
}
if ([cell respondsToSelector:#selector(setLayoutMargins:)])
{
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 144.0;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)btnClickedPostData:(id)sender {
NSString *tokenString = #"65d188d3f0ab52487001c331584ac819";
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
[defaultConfigObject setHTTPAdditionalHeaders:#{ #"token" : tokenString}];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
NSURL *url = [NSURL URLWithString:#"YOUR URL"];
NSString *paramString = #"lang=en&title=&start=&end=";
NSData *httpBody = [paramString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:60.0];
NSString *msgLength = [NSString stringWithFormat:#"%lu", (unsigned long)[httpBody length]];
[urlRequest addValue: #"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setHTTPMethod:#"POST"];
//[urlRequest setAllHTTPHeaderFields:paramString];
[urlRequest setAllHTTPHeaderFields:#{ #"token" : tokenString}];
[urlRequest setHTTPBody:httpBody];
//[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSError *parseError = nil;
NSHTTPURLResponse* respHttp = (NSHTTPURLResponse*) response;
if (!error && respHttp.statusCode == 200) {
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSMutableArray *arrArray = [responseDictionary objectForKey:#"newslist"];
NSString *title = [NSString stringWithFormat:#"%#", [arrArray valueForKey:#"title"]];
UIAlertView *alert =[[UIAlertView alloc] initWithTitle:#"Details" message:title delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:#"Cancel", nil];
[alert show];
NSLog(#"%#", arrArray);
}else{
NSLog(#"%#", error);
}
}];
[dataTask resume];
}
#end
//CustomeTableviewCell With XIB
**ResponseTableViewCell.h**
#import <UIKit/UIKit.h>
#interface ResponseTableViewCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UILabel *lblCatID;
#property (weak, nonatomic) IBOutlet UILabel *lblEventName;
#property (weak, nonatomic) IBOutlet UILabel *lblCreateDate;
#end
**ResponseTableViewCell.m**
#import "ResponseTableViewCell.h"
#implementation ResponseTableViewCell
#synthesize lblCatID,lblEventName,lblCreateDate;
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
// and also download and check JSON demo : https://drive.google.com/open?id=0B0rS2ZVDMVRiSmJJb1BuQklJSzA[Click to show JSON demo Hear][1]
//add custom table view cell with custom table cell and add label to display information. i used pod to setup AFNetworking.
and also download and check JSON demo : https://drive.google.com/open?id=0B0rS2ZVDMVRiSmJJb1BuQklJSzAClick to show JSON demo Hear
Can anyone suggest a way to do this.me how the things will be done.
You Can use also use sqlite for the data.

Can't get data on detailviewcontroller with Hpple parsing

I am a beginner in Obj-C and I try to make an app with this raywenderlich tutorial.
I parse html page with Title of articles (mininglife.ru) , also I getting an urls of each articles and keep it in an NSMutableArray for using it in my DetailviewController.
But when I try to pull urls off and put it in NSUrl nothing happens. I've tried a lot of ways, Can you help me with it and try to explain if I do something wrong. Thank you.
-(void)loadArticles{
Articlelist *urlOfArticle = [_objects objectAtIndex:self]; // from previous parsing
NSURL *articleUrl = [NSURL URLWithString:urlOfArticle.url];// I think this string is wrong, or?
NSData *htmlUrlsData = [NSData dataWithContentsOfURL:articleUrl];
TFHpple *articleParser = [TFHpple hppleWithHTMLData:htmlUrlsData];
NSString *articleNameXpath = #"/html/body/div[1]/div/div[1]/main/article/h1";
// NSString *articleContentXpath = #"//div[#class'entry-content']//p";
NSArray *articleNameNodes = [articleParser searchWithXPathQuery:articleNameXpath];
// NSArray *articleContentNodes = [articleParser searchWithXPathQuery:articleContentXpath];
NSMutableArray *newArticleArray = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in articleNameNodes) {
Article *newArticleName = [[Article alloc] init];
[newArticleArray addObject:newArticleName];
newArticleName.name = [[element firstChild] content];
}
_articleName = newArticleArray;
[self.tableView reloadData];
}
Change interface to this
#interface MasterViewController () {
NSMutableArray *_articles;
}
#end
Add this to MasterViewController
- (void)loadArticles
{
NSURL *articlesUrl = [NSURL URLWithString:#"http://mininglife.ru"];
NSData *articlesHtmlData = [NSData dataWithContentsOfURL:articlesUrl];
TFHpple *articlesParser = [TFHpple hppleWithHTMLData:articlesHtmlData];
NSString *articlesXpathQueryString = #"/html/body/div[1]/div/div[1]/main/article/h1";
NSArray *articlesNodes = [articlesParser searchWithXPathQuery:articlesXpathQueryString];
NSMutableArray *newArticles = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in articlesNodes) {
Article *article = [[Article alloc] init];
[newArticles addObject:article];
article.title = [[element firstChild] content];
article.url = [element objectForKey:#"href"];
}
_articles = newArticles;
[self.tableView reloadData];
}
Change DetailviewController.h's interface to
#class Article;
#interface DetailViewController : UIViewController
#property (strong, nonatomic) Article *article;
#property (strong, nonatomic) IBOutlet UILabel *detailDescriptionLabel;
#end
Change DetailViewController.m to
#import "DetailViewController.h"
#import "Article.h"
#import "TFHpple.h"
#implementation DetailViewController
#synthesize detailDescriptionLabel = _detailDescriptionLabel;
- (void)viewDidLoad
{
[super viewDidLoad];
[self loadArticle];
}
- (void)loadArticle
{
NSURL *articleUrl = [NSURL URLWithString:self.article.url];
NSData *articleHtmlData = [NSData dataWithContentsOfURL:articleUrl];
TFHpple *articleParser = [TFHpple hppleWithHTMLData:articleHtmlData];
NSString *articleXpathQueryString = #"//div[#class'entry-content']//p";
NSArray *articleNodes = [articleParser searchWithXPathQuery:articleXpathQueryString];
NSMutableArray *newArticleContents = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in articleNodes) {
[newArticleContents addObject:[[element firstChild] content]];
}
NSLog(#"%#", newArticleContents);
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"Detail", #"Detail");
}
return self;
}
#end
Don't forget to change all call to loadTutorials to loadArticles in MasterViewController. PS: This example only prints the articles content to the console
Your xPath might be wrong as well

Not able to read some json files where they are downloaded and saved via url in ios7

Im having issues with this code reading some .json files, it works fine on json that can be read via IE like a webpage but wont work on files that the url is tring to download them like a ftp style.
In the end im looking at populating labels with the json info once this works but cant see what around the URLRequest is causing it.
This is what code im testing it with:
// WDViewController.h
#import <UIKit/UIKit.h>
#interface WDViewController : UIViewController{
NSArray *jsonArray;
NSMutableData *data;
}
#property (weak, nonatomic) IBOutlet UILabel *outputLabel;
-(IBAction)WDPlayerButtonUpdate:(id)sender;
#end
// WDViewController.m
#import "WDViewController.h"
#interface WDViewController ()
#end
#implementation WDViewController
#synthesize outputLabel;
-(IBAction)WDPlayerButtonUpdate:(id)sender{
NSURL *url = [NSURL URLWithString:#"http://gooruism.com/feed/json"];
NSURLRequest *data = [NSURLRequest requestWithURL:url];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
data = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData{
[data appendData:theData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:nil error:nil];
// Loop through jsonArray
for (int i = 0; i< jsonArray.count; i++)
{
outputLabel.text = [[jsonArray objectAtIndex:i] objectForKey:#"889"]; // Set Labels
}
}
#end
The json file and url are just one that I found looking for a solution via Google and are only for testing.
After a lot more Google and learning some more about json,
Ive got the code working.
Ended up being more of a null exemption from empty indexes and not calling objectForKeys correctly, as was leaving strings that errored when then using to populate a label.
Code I finally got to work:
//
// WDViewController.m
// JSON Test
#import "WDViewController.h"
#interface WDViewController ()
#end
#implementation WDViewController
#synthesize testLabel;
-(IBAction)WDPlayerButtonUpdate:(id)sender
{
// Set network activity indicator
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
// Set json url.
NSURL *url = [NSURL URLWithString:#"<url for json>"];
// get the url page into the nsdata object.
NSData *jsonData = [NSData dataWithContentsOfURL:url];
// Read json (from jasondata) and convert to object.
if ( jsonData != nil)
{
NSError *error = nil;
id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
if (error == nil)
NSLog (#"%#", result);
NSLog(#"Test 1");
// Retrieve array and show in log
NSLog(#"From status index: %#", [result objectForKey:#"status"]);
// Retrieve data and log
NSLog(#"From profile.handle index: %#", [[result objectForKey:#"profile"]objectForKey:#"handle"]);
NSLog(#"Next Test 2"); // Populate label with data handle
yestLabel.text = [[result objectForKey:#"profile"]objectForKey:#"handle"];
NSLog(#"End of Tests");
}
}
#end

UISearchBar in Xcode 5

I implemented the UISearchBar option in my Json data table. However, whenever I am trying to search it, the program crashes. Highly appreciate help on this.
my table view controller's header and implementation files are given below
Header file.
#import <UIKit/UIKit.h>
#interface byTitleViewController : UITableViewController
#property (nonatomic, strong) NSMutableArray * jsonArray;
#property (nonatomic, strong) NSMutableArray * songsArray;
#property (strong, nonatomic) NSMutableArray* filteredTableData;
- (void) retriveData;
#property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
#property (nonatomic, assign) bool isFiltered;
#end
Implementation file
#import "byTitleViewController.h"
#import "songs.h"
#define getDataURL #"http://fetchpin.com/byTitle.php"
#interface byTitleViewController ()
#end
#implementation byTitleViewController
#synthesize jsonArray, songsArray, filteredTableData, searchBar, isFiltered;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"By Title";
searchBar.delegate = (id)self;
[self retriveData];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSUInteger rowCount;
if(self.isFiltered)
rowCount = filteredTableData.count;
else
rowCount = songsArray.count;
return rowCount;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
songs* songlist;
if (isFiltered) {
songlist = [filteredTableData objectAtIndex:indexPath.row];
}else{
songlist = [songsArray objectAtIndex:indexPath.row];
}
cell.textLabel.text = songlist.songTitle;
return cell;
// Configure the cell...
/*songs * songObject;
songObject = [songsArray objectAtIndex:indexPath.row];
cell.textLabel.text = songObject.songTitle;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
*/
}
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void) retriveData{
NSURL * url = [NSURL URLWithString:#"http://fetchpin.com/byTitle.php"];
NSData * data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
songsArray = [[NSMutableArray alloc] init];
for (int i = 0; i < jsonArray.count; i++) {
NSString * sId = [[jsonArray objectAtIndex:i] objectForKey:#"id"];
NSString * sTitle = [[jsonArray objectAtIndex:i] objectForKey:#"title"];
[songsArray addObject:[[songs alloc]initWithSongTitle: sTitle andSongID: sId]];
}
//[self.tableView reloadData];
}
//search bar ...
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
if(text.length == 0)
{
isFiltered = FALSE;
}
else
{
isFiltered = true;
filteredTableData = [[NSMutableArray alloc] init];
for (songs * sTitle in songsArray)
{
NSRange titleRange = [sTitle.songTitle rangeOfString:text options:NSCaseInsensitiveSearch];
if(titleRange.location != NSNotFound)
{
[filteredTableData addObject:sTitle];
}
}
}
[self.tableView reloadData];
}
#end
It looks like the problem is that some of the objects you are loading from the JSON have a title that is not an NSString, but an NSNull. Adding a check for NSNull in the textDidChange: method should solve the problem:
if(![sTitle.name isKindOfClass:[NSNull class]])
{
NSRange titleRange = [sTitle.name rangeOfString:text options:NSCaseInsensitiveSearch];
if(titleRange.location != NSNotFound)
{
[filteredTableData addObject:sTitle];
}
}
Alternately, you could filter out songs with an NSNull title in your retrieveData method.

Cannot get UISearchBar code working

xcode newbie trying to get UISearchBar functionality working.
I am using storyboards and my tableview controller shows a list of events (title, location & start date)in the cells from the array json. When the table firsts loads all of my results are displayed ok. When I click put some text into the search bar (text that exists in the title) nothing is shown in the view controller (I.e. it filters all of the events out). Hopefully this makes a bit more sense.
My header file is
#import <UIKit/UIKit.h>
#define kGETUrl #"http://www.max-momentus.com/fetchevents.php5"
#interface MMAllEventsViewController : UITableViewController <UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource> {
NSMutableArray *json;
NSMutableArray *jsonFiltered;
BOOL isFiltered;
}
#property (weak, nonatomic) IBOutlet UISearchBar *eventSearchBar;
#property (strong, nonatomic) IBOutlet UITableView *eventTableView;
#property (strong, nonatomic) NSString *categorySelected;
#property (strong, nonatomic) NSString *displayDate;
#end
My implementation file is
#import "MMAllEventsViewController.h"
#import "MMEventDetailViewController.h"
#import "MMCategoryViewController.h"
#import "MMEventCell.h"
#interface MMAllEventsViewController ()
#end
#implementation MMAllEventsViewController
#synthesize categorySelected, displayDate;
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"EventDetailSegue"]) {
// Segue code
}
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
-(void) getData:(NSData *) data {
NSError *error;
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
[self.tableView reloadData];
}
-(void) start {
NSURL *url = [NSURL URLWithString:kGETUrl];
NSData *data = [NSData dataWithContentsOfURL:url];
[self getData:data];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.eventSearchBar.delegate = self;
self.eventTableView.delegate = self;
self.eventTableView.dataSource = self;
[self start];
}
-(void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if (searchText.length == 0) {
isFiltered = NO;
}
else {
isFiltered = YES;
for (int i = 0; i < [json count]; i++)
{
NSMutableDictionary *temp = (NSMutableDictionary*) [json objectAtIndex:i];
NSString *name = [NSString stringWithFormat:#"%#", [temp valueForKey:#"Title"]];
NSRange r = [name rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(r.location != NSNotFound)
{
[jsonFiltered addObject:name];
}
i++;
}
}
[self.eventTableView reloadData];
}
-(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[self.eventTableView resignFirstResponder];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (isFiltered) {
return [jsonFiltered count];
}
return [json count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"EventCell";
MMEventCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[MMEventCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
if (!isFiltered) {
NSDictionary *info = [json objectAtIndex:indexPath.row];
cell.eventTitleLabel.text = [info objectForKey:#"Title"];
cell.locationLabel.text = [info objectForKey:#"Location"];
NSString *startDate = [info objectForKey:#"StartDate"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *sdate = [dateFormatter dateFromString:startDate];
[dateFormatter setDateFormat:#"EEE, d MMM yy"];
NSString *convertedStartDate = [dateFormatter stringFromDate:sdate];
NSString *endDate = [info objectForKey:#"EndDate"];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *edate = [dateFormatter dateFromString:endDate];
[dateFormatter setDateFormat:#"EEE, d MMM yy"];
NSString *convertedEndDate = [dateFormatter stringFromDate:edate];
if([sdate isEqualToDate:edate]) {
displayDate = convertedStartDate;
} else {
displayDate = [convertedStartDate stringByAppendingString:#" to "];
displayDate = [displayDate stringByAppendingString:convertedEndDate];
}
cell.datesLabel.text = displayDate;
}
else {
NSDictionary *info = [jsonFiltered objectAtIndex:indexPath.row];
cell.eventTitleLabel.text = [info objectForKey:#"Title"];
cell.locationLabel.text = [info objectForKey:#"Location"];
NSString *startDate = [info objectForKey:#"StartDate"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *sdate = [dateFormatter dateFromString:startDate];
[dateFormatter setDateFormat:#"EEE, d MMM yy"];
NSString *convertedStartDate = [dateFormatter stringFromDate:sdate];
NSString *endDate = [info objectForKey:#"EndDate"];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *edate = [dateFormatter dateFromString:endDate];
[dateFormatter setDateFormat:#"EEE, d MMM yy"];
NSString *convertedEndDate = [dateFormatter stringFromDate:edate];
if([sdate isEqualToDate:edate]) {
displayDate = convertedStartDate;
} else {
displayDate = [convertedStartDate stringByAppendingString:#" to "];
displayDate = [displayDate stringByAppendingString:convertedEndDate];
}
cell.datesLabel.text = displayDate;
}
return cell;
}
#end
Have you made sure you have the delegates: in your view controllers .h file? Also, make sure you've selected the "UISearchBar and UISearchDisplay Controller" as your search bar object from the storyboard (assuming you're using storyboards). Make sure you've linked your SearchBar to have your view controller be its delegate, and it's connected to an IBOutlet object in your code (again, assuming your using storyboards:
#property (strong, nonatomic) IBOutlet UISearchBar *searchBar;
Finally, make that you have declared a UISearchDisplayController variable, linked it to your UITableView and then make sure when loading the results from a search, to check in your
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
and
- (NSInteger)numberOfRowsInTableView:(UITableView *)tableView
if:
if(tableView == searchDisplay):
{
...load results.
}
else
{
...load normal view
}