json photo path xcode - objective-c

i can't get my photo in json, did i haven't something wrong to get that? i already check my photo url in php,it works,
in my tableview.m file:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
DetailHomeViewController * dvc = [[DetailHomeViewController alloc]init];
HomeDetail * currentHome = [HomeArray objectAtIndex:indexPath.row];
dvc.photodetail = currentHome.photo_path;
NSURL *url = [NSURL URLWithString:dvc.photodetail];
NSData *data = [NSData dataWithContentsOfURL:url];
dvc.photolabel.image = [UIImage imageWithData:data];
[self presentViewController:dvc animated:YES completion:nil];
}
#pragma mark - Methods
- (void) retrieveData
{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSURL * url = [NSURL URLWithString:getDataURL];
NSData * data = [NSData dataWithContentsOfURL:url];
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
HomeArray = [[NSMutableArray alloc]init];
for (int i = 0; i < json.count; i++)
{
NSString * photo = [[json objectAtIndex:i] objectForKey:#"photo_path"];
HomeDetail * home2 = [[HomeDetail alloc]initWithPhoto_path:photo];
[HomeArray addObject:home2];
}
[self.myTableView reloadData];
}
my HomeDetail.h file:(Json file)
#property (nonatomic, strong) NSString * photo_path;
//Methods
- (id) initWithPhoto_path: (NSString *) photo ;
my HomeDetail.m file:
- (id) initWithPhoto_path: (NSString *) photo ;
{
self = [super init];
if (self)
{photo_path = photo;}
return self;
}
my DetailHomeViewController.h file:
#property (nonatomic, strong) NSString * photodetail;
#property (strong, nonatomic) IBOutlet UIImageView *photolabel;
my DetailHomeViewController.m file:
- (void)viewDidLoad
{
[super viewDidLoad];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
// photolabel.image = photodetail;
NSURL *url = [NSURL URLWithString:photodetail];
NSData *data = [NSData dataWithContentsOfURL:url];
photolabel.image = [UIImage imageWithData:data];
}
and here is my json data:
[{"id":"2","detail_english":" TESTING_DETAIL","photo_path":"img\/uploads\/news\/news_20150320075842.png","date":"2013-10-15"‌​,"display_stat":"1","news_order":"1"},
{"id":"5","detail_english":"empty","photo_path":"img\/uploads\/news\/news_20150323105547.png","date":"2015-03-20","display_stat":"1","news_order":"1"}]

Your photo path is not a full url, you need to append the domain name.
So you string would look like this:
http://www.domain.com/img/uploads/news/news_20150323105547.png

Related

Search Bar based on JSON not working

I have a TableViewController and array from JSON url. I wanted to search #Name from server.Tableview showing data were well.But searching does not working.How to do it ?Where is the mistake?
Tableviewcontroller.h :
#interface CitiesViewController ()
#property(nonatomic,strong)NSMutableArray *jsonArray
#property(nonatomic,strong)NSMutableArray *citiesArray;
#property (nonatomic, copy)NSMutableArray *filteredNames;
#property (nonatomic, strong)UISearchController *searchController;
#property (strong, readwrite, nonatomic) NSMutableArray *arrayPlace;
#property (weak, nonatomic) IBOutlet UISearchBar *searcBar;
-(void)retrieveData;
Tableviewcontroller.m :
#end
#implementation CitiesViewController
#synthesize
citiesArray,jsonArray,filteredNames,arrayPlace,searcBar,searchController;
#pragma mark -
#pragma mark Class Methods
-(void)retrieveData
{
NSURL *url = [NSURL URLWithString:getDataURL];
NSData *data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
citiesArray =[[NSMutableArray alloc]init];
for (int i= 0; i<jsonArray.count; i++)
{
NSString *cID = [[jsonArray objectAtIndex:i] objectForKey:#"id"];
NSString *cName = [[jsonArray objectAtIndex:i] objectForKey:#"Name"];
NSString *cCompany = [[jsonArray objectAtIndex:i] objectForKey:#"company"];
NSString *cPosition = [[jsonArray objectAtIndex:i] objectForKey:#"position"];
NSString *cEmail = [[jsonArray objectAtIndex:i] objectForKey:#"email"];
NSString *cNumber = [[jsonArray objectAtIndex:i] objectForKey:#"number"];
NSString *cPhoto = [[jsonArray objectAtIndex:i] objectForKey:#"photo"];
NSURL *urlOne = [NSURL URLWithString:cPhoto];
// NSLog(#"%#",urlOne);
NSData *photoData = [NSData dataWithContentsOfURL:urlOne];
UIImage *imageOne = [[UIImage alloc] initWithData:photoData];
[citiesArray addObject:[[City alloc]initWithCityName:cName andCityState:cCompany andCityCountry:cEmail andCityPopulation:cPosition andCityID:cID andCityNumber:cNumber andCityPhoto: (UIImage *) imageOne]];
}
[self.tableView reloadData];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self retrieveData];
self.arrayPlace = [NSMutableArray new];
UITableView *tableView = (id)[self.view viewWithTag:1];
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"Cell"];
filteredNames = [[NSMutableArray alloc]init];
searchController = [[UISearchController alloc]init];
self.searchController.searchResultsUpdater = self;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView.tag == 1) {
return citiesArray.count;
} else {
return [filteredNames count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
// Configure the cell...
if (tableView.tag == 1){
City *cityob;
cityob=[citiesArray objectAtIndex:indexPath.row];
cell.textLabel.text=cityob.employeeName;
}else{
cell.textLabel.text = filteredNames[indexPath.row];
}
return cell;
}
#pragma mark Search Display Delegate Methods
-(void)searchDisplayController:(UISearchController *)controller didLoadSearchResultsTableView:(UITableView *)tableView {
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"Cell"];
}
-(BOOL)searchDisplayController:(UISearchController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[filteredNames removeAllObjects];
if (searchString.length > 0) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains [search] %#", self.searcBar.text];
for (NSString *name in citiesArray) {
NSArray *matches = [[self.jsonArray[name] objectForKey:#"Name"]filteredArrayUsingPredicate:predicate];
[filteredNames addObjectsFromArray:matches];
}
NSLog(#"filteredNames==%#",filteredNames);
}
return YES;
}

Which third party Imageview class should i used?

My requirement is :
Need to show image in imageview from server URL & save it for offline use also.
But There may be chances that same URL image can be updated.
I tried EGOImageview,AsyncImageview,FXImageview,Haneke thsese all classes i tried.
my first part of requirement is achieved. but not second..i.e if "xxxxx" link image is shown for first time....if on that same link image is upadated ,app shows old image only...
You can use the below class that will full fill your requirement
DImageView.h
#import <UIKit/UIKit.h>
#interface DImageView : UIImageView
#property (nonatomic, strong) UIActivityIndicatorView *activityView;
- (void)processImageDataWithURLString:(NSString *)urlString;
+ (UIImage *)getSavedImage :(NSString *)fileName;
+ (void)saveImageWithFolderName:(NSString *)folderName AndFileName:(NSString *)fileName AndImage:(NSData *) imageData;
DImageView.m
#import "DImageView.h"
#define IMAGES_FOLDER_NAME #"DImages"
#implementation DImageView
#pragma mark - App Life Cycle
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
}
return self;
}
- (void)dealloc
{
self.activityView = nil;
[super dealloc];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self)
{
[self initWithFrame:[self frame]];
}
return self;
}
#pragma mark - Download images
- (void)processImageDataWithURLString:(NSString *)urlString //andBlock:(void (^)(UIImage * img))processImage
{
#autoreleasepool
{
UIImage * saveImg = [DImageView getSavedImage:urlString];
if (saveImg)
{
dispatch_queue_t callerQueue = dispatch_get_main_queue();
dispatch_async(callerQueue, ^{
#autoreleasepool
{
[self setImage:saveImg];
}
});
}
else
{
[self showActivityIndicator];
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
dispatch_queue_t callerQueue = dispatch_get_main_queue();
dispatch_queue_t downloadQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0);
__block NSError* error = nil;
dispatch_async(downloadQueue, ^{
NSData * imageData = [[[NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error] retain] autorelease];
if (error)
{
NSLog(#"DImg Error %#", [error debugDescription]);
}
else
{
dispatch_async(callerQueue, ^{
#autoreleasepool
{
UIImage *image = [UIImage imageWithData:imageData];
[self setImage:image];
[self hideActivityIndicator];
/* Below code is to save image*/
[DImageView saveImageWithFolderName:IMAGES_FOLDER_NAME AndFileName:urlString AndImage:imageData];
}
});
}
});
dispatch_release(downloadQueue);
}
}
}
#pragma mark - File Save methods
+ (void)saveImageWithFolderName:(NSString *)folderName AndFileName:(NSString *)fileName AndImage:(NSData *) imageData
{
#autoreleasepool
{
NSFileManager *fileManger = [NSFileManager defaultManager] ;
NSString *directoryPath = [NSString stringWithFormat:#"%#/%#",[DImageView applicationDocumentsDirectory],folderName] ;
if (![fileManger fileExistsAtPath:directoryPath])
{
NSError *error = nil;
[fileManger createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:&error];
}
fileName = [DImageView fileNameValidate:fileName];
NSString *filePath = [NSString stringWithFormat:#"%#/%#",directoryPath,fileName] ;
BOOL isSaved = [imageData writeToFile:filePath atomically:YES];
if (!isSaved)
{
NSLog(#" ** Img Not Saved");
}
}
}
+ (NSString *)applicationDocumentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
+ (UIImage *)getSavedImage :(NSString *)fileName
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
fileName = [DImageView fileNameValidate:fileName];
NSFileManager * fileManger = [NSFileManager defaultManager] ;
NSString * directoryPath = [NSString stringWithFormat:#"%#/%#",[DImageView applicationDocumentsDirectory],IMAGES_FOLDER_NAME] ;
NSString * filePath = [NSString stringWithFormat:#"%#/%#",directoryPath,fileName] ;
if ([fileManger fileExistsAtPath:directoryPath])
{
UIImage *image = [UIImage imageWithContentsOfFile:filePath] ;
if (image)
{
return image;
}
else
{
NSLog(#"** Img Not Found **");
return nil;
}
}
[pool release];
return nil;
}
+ (NSString*) fileNameValidate : (NSString*) name
{
name = [name stringByReplacingOccurrencesOfString:#"://" withString:#"##"];
name = [name stringByReplacingOccurrencesOfString:#"/" withString:#"#"];
name = [name stringByReplacingOccurrencesOfString:#"%20" withString:#""];
return name;
}
#pragma mark - Activity Methods
- (void) showActivityIndicator
{
self.activityView = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
self.activityView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin;
self.activityView.hidesWhenStopped = TRUE;
self.activityView.backgroundColor = [UIColor clearColor];
self.activityView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
[self addSubview:self.activityView];
[self.activityView startAnimating];
}
- (void) hideActivityIndicator
{
CAAnimation *animation = [NSClassFromString(#"CATransition") animation];
[animation setValue:#"kCATransitionFade" forKey:#"type"];
animation.duration = 0.4;;
[self.layer addAnimation:animation forKey:nil];
[self.activityView stopAnimating];
[self.activityView removeFromSuperview];
for (UIView * view in self.subviews)
{
if([view isKindOfClass:[UIActivityIndicatorView class]])
[view removeFromSuperview];
}
}
What will this class do ?
It will download images from server and save it to application document directory And get it from local if its available.
How to use that ?
Set DImageView class in your nib file for UIImageView.
Then you can simply use it as below in your .m file.
[imgViewName processImageDataWithURLString:imageURl];
You should take a look at SDWebImage. It's one of the most used UIImageView category right now and offers a lot of features, including caching.
Have a look at this part of the documentation to learn how to refresh your cache with it: Handle image refresh

MKMapView pin animation and annotation

I'm using the google places API to find some restaurants nearby (based on current location using core location manager); currently, I'm able to drop pins. I use the searchBarSearchButtonClicked method, and inside of a dispatch_async block, I call my method to parse through my serialized data and attribute values to properties of my pin class (class MKAnnotation). I'd like to animate my pin drops, and also actually display annotations...for some reason I had them working before but now they won't show up when I click on the pins.
VIEW CONTROLLER.H
#interface MyViewController : UIViewController <CLLocationManagerDelegate, MKMapViewDelegate, UISearchBarDelegate,NSURLSessionDelegate> {
CLLocationManager *locationManager;
}
#property (strong, nonatomic) MKMapView *mapView;
#property (strong, nonatomic) UISearchBar *searchBar;
#property (strong, nonatomic) UIImageView *logo;
#property (strong, nonatomic) UIToolbar *toolBar;
#property (strong, nonatomic) NSString *places;
#end
VIEW CONTROLLER.M
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
NSLog(#"%#", self.searchBar.text);
NSURLSession *session = [NSURLSession sharedSession];
NSString *s = [NSString
stringWithFormat:#"https://maps.googleapis.com/maps/api/place/nearbysearch/json?keyword=%#&location=%f,%f&radius=5&types=food&key=AIzaSyCg6Ahz_hQ1f2rjKEAWcJKQetblPVjHS-E", self.searchBar.text, locationManager.location.coordinate.latitude, locationManager.location.coordinate.longitude];
NSURL *url = [[NSURL alloc]initWithString:s];
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
NSData *dataResponse = [[NSData alloc]initWithContentsOfURL:location];
NSDictionary *dictionaryReponse = [NSJSONSerialization JSONObjectWithData:dataResponse options:kNilOptions error:&error];
NSMutableArray *finalResults = [dictionaryReponse objectForKey:#"results"];
dispatch_async(dispatch_get_main_queue(), ^{
[self placeAnnotations:finalResults];
});
}];
[task resume];
}
-(void)placeAnnotations:(NSMutableArray *)data {
for (id<MKAnnotation> annotation in self.mapView.annotations) {
// if ([annotation isKindOfClass:[MapPoint class]]) {
[self.mapView removeAnnotation:annotation];
// }
}
for (int i = 0; i < [data count]; i++) {
NSDictionary *place = [data objectAtIndex:i];
NSDictionary *geo = [place objectForKey:#"geometry"];
NSDictionary *location = [geo objectForKey:#"location"];
NSString *name = [place objectForKey:#"name"];
NSString *vicinity = [place objectForKey:#"vicinity"];
CLLocationCoordinate2D placeCoord;
placeCoord.latitude = [[location objectForKey:#"lat"] doubleValue];
placeCoord.longitude = [[location objectForKey:#"lng"] doubleValue];
MapPoint *newPin = [MapPoint new];
newPin.name = name;
newPin.address = vicinity;
newPin.coordinate = placeCoord;
MKPinAnnotationView *newAnnotation = [[MKPinAnnotationView alloc]initWithAnnotation:newPin reuseIdentifier:#"annotation"];
newAnnotation.animatesDrop = YES;
[self.mapView addAnnotation:newPin];
}
[self.mapView reloadInputViews];
}
I

MPMoviePlayerController endless loading (filepicker)

I am trying to stream a video uploaded on filepicker, but it keeps loading without playing the video.
The link is: https://www.filepicker.io/api/file/fLayj5bYTWuso1TVNknv
The page is a video/mp4 page, but as you can see there is no extension for the page.
The Code:
#interface RTVideo()
#property (nonatomic,strong) MPMoviePlayerController *moviePlayer;
#end
#implementation RTVideo
UIView *frame;
-(void)play
{
NSNumber *adId = 5 ;
NSString *session = [[NSUserDefaults standardUserDefaults]stringForKey:#"sessionID"];
NSString *type = #"video";
[NetworkManagerCenter retrievePageWithtype:type
Id:adId
session:session
success:^(RT *ad) {
[self playAD];
} failure:^(NSError *error) {
[self removeFromSuperview];
}];
}
-(void)playAD
{
frame = self;
NSURL *movieURL = [NSURL URLWithString: #"https://www.filepicker.io/api/file/fLayj5bYTWuso1TVNknv"];
self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
[frame addSubview:self.moviePlayer.view];
self.moviePlayer.fullscreen = YES;
self.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
self.moviePlayer.initialPlaybackTime = -1.0;
[self.moviePlayer prepareToPlay];
[self.moviePlayer play];
}
#end
Is this not working because there is no extension and how can I solve this?

Access properties and methods from one class inside another class in Objective C

I am trying to build a class in Objective C that contain serve the web service and database methods for my application. In this class I want to call a web service and grab employee records and then load them into an SQL table for later use in a view.
I got this working when all the code as in the view, but in trying to make this new class (what I am calling GetEmployee) I am running into problems. I do not understand well how to access properties and methods from one class in another.
Here is my GetEmployee Class
#import <Foundation/Foundation.h>
#import "employee.h"
#import "FMDatabase.h"
#import "FMDatabaseAdditions.h"
#import "FMDatabasePool.h"
#import "FMDatabaseQueue.h"
#import "FMResultSet.h"
#import "Utility.h"
#interface GetEmployee : NSObject
{
NSMutableArray *employees;
}
#property (nonatomic, copy) NSString *databaseName;
#property (nonatomic, copy) NSString *databasePath;
- (void)updateEmployeeData;
- (void)callWebService;
- (void)fetchedData:(NSData *)responseData;
- (NSMutableArray *) getEmployees;
#end
implementation
#define kBgQueue dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define scoularDirectoryURL [NSURL URLWithString: #"https://XXXXXXXXX/mobile/mobilede.nsf/restServices.xsp/PeopleByName"]
#import "GetEmployee.h"
#import "FMDatabase.h"
#import "FMDatabaseAdditions.h"
#import "FMResultSet.h"
#implementation GetEmployee
- (id) init
{
if (self = [super init])
{
self.databaseName = #"employees.db";
}
return self;
}
#pragma
- (void)updateEmployeeData{
//Delete database if it exists and then copy fresh DB
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [documentPaths objectAtIndex:0];
self.databasePath = [documentDir stringByAppendingPathComponent:self.databaseName];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL success;
success = [fileManager fileExistsAtPath:self.databasePath];
if (success) {
[fileManager removeItemAtPath:self.databasePath error:nil];
}
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:self.databaseName];
[fileManager copyItemAtPath:databasePathFromApp toPath:self.databasePath error:nil];
//Call the web service
[self callWebService];
[self populateDatabase];
}
- (void) callWebService {
dispatch_sync(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:
scoularDirectoryURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
NSError* error;
NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData: responseData options: NSJSONReadingMutableContainers error: &error];
id jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
employees = [[NSMutableArray alloc] init];
if (!jsonArray) {
} else {
for (jsonObject in jsonArray){
employee *thisEmployee = [employee new];
thisEmployee.fullName = [jsonObject objectForKey:#"$13"];
thisEmployee.ste = [jsonObject objectForKey:#"state"];
thisEmployee.city = [jsonObject objectForKey:#"city"];
[employees addObject:thisEmployee];
}
}
}
-(void) populateDatabase {
////Call the web service and populate the db
//dispatch_sync(kBgQueue, ^{
// NSData* data = [NSData dataWithContentsOfURL:
// scoularDirectoryURL];
// [self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
//});
//Populate the db
FMDatabase *db = [FMDatabase databaseWithPath:[Utility getDatabasePath]];
[db open];
for (employee *thisemployee in employees) {
BOOL success = [db executeUpdate:#"INSERT INTO employees (fullname,city,state) VALUES (?,?,?);",thisemployee.fullName,thisemployee.city,thisemployee.ste, nil];
if (success) {} // Only to remove success error
}
[db close];
}
- (NSMutableArray *) getEmployees
{
//NSMutableArray *employees = [[NSMutableArray alloc] init];
employees = [[NSMutableArray alloc] init];
FMDatabase *db = [FMDatabase databaseWithPath:[Utility getDatabasePath]];
[db open];
FMResultSet *results = [db executeQuery:#"SELECT * FROM employees"];
while([results next])
{
employee *thisEmployee = [employee new];
thisEmployee.fullName = [results stringForColumn:#"fullname"];
thisEmployee.city = [results stringForColumn:#"city"];
thisEmployee.ste = [results stringForColumn:#"state"];
[employees addObject:thisEmployee];
}
[db close];
return employees;
}
#end
And here is the MasterViewController
header
#import <UIKit/UIKit.h>
#import "employee.h"
#import "FMDatabase.h"
#import "FMResultSet.h"
#import "FMDatabaseAdditions.h"
#import "Utility.h"
#import "GetEmployee.h"
#interface MasterViewController : UITableViewController
{
NSMutableArray *employees;
//GetEmployee *ScoularEmployees;
}
#end
implementation
#define kBgQueue dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define scoularDirectoryURL [NSURL URLWithString: #"https://xxxxxxxx/mobile/mobilede.nsf/restServices.xsp/PeopleByName"]
#import "MasterViewController.h"
#import "DetailViewController.h"
#import "employee.h"
#import "GetEmployee.h"
#interface MasterViewController () {
NSMutableArray *_objects;
}
#property(strong, nonatomic) GetEmployee *ScoularEmployees;
#end
#implementation MasterViewController
- (void)awakeFromNib
{
[super awakeFromNib];
}
- (void)viewDidLoad
{
[super viewDidLoad];
//GetEmployee *ScoularEmployees = [[GetEmployee alloc] init];
[self.ScoularEmployees init];
//[self.ScoularEmployees init];
//_ScoularEmployees = [[GetEmployee alloc] init];
//[_ScoularEmployees getEmployees];
//GetEmployee *ScoularEmployees = [[GetEmployee alloc] init];
//GetEmployee *thisEmployeeData = [[GetEmployee alloc] init];
//[self.ScoularEmployees updateEmployeeData];
//[self.ScoularEmployees getEmployees];
//[ScoularEmployees updateEmployeeData];
//[ScoularEmployees getEmployees];
}
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return employees.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
NSString *fullName = [[employees objectAtIndex:indexPath.row] valueForKey:#"fullName"];
cell.textLabel.text = fullName;
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
[_objects removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"showDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
employee *dtlEmployee = [employees objectAtIndex:indexPath.row];
[[segue destinationViewController] setDetailItem:dtlEmployee];
}
}
- (void)fetchedData:(NSData *)responseData {
NSError* error;
NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData: responseData options: NSJSONReadingMutableContainers error: &error];
id jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
//employees = [[NSMutableArray alloc] init];
if (!jsonArray) {
} else {
//NSMutableArray *employees = [[NSMutableArray alloc ]init];
for (jsonObject in jsonArray){
employee *thisEmployee = [employee new];
thisEmployee.fullName = [jsonObject objectForKey:#"$13"];
thisEmployee.ste = [jsonObject objectForKey:#"state"];
thisEmployee.city = [jsonObject objectForKey:#"city"];
[employees addObject:thisEmployee];
}
}
}
//-(NSMutableArray *) getEmployees
//{
//NSMutableArray *employees = [[NSMutableArray alloc] init];
//employees = [[NSMutableArray alloc] init];
// FMDatabase *db = [FMDatabase databaseWithPath:[Utility getDatabasePath]];
// [db open];
// FMResultSet *results = [db executeQuery:#"SELECT * FROM employees"];
//
// while([results next])
// {
// employee *thisEmployee = [employee new];
// thisEmployee.fullName = [results stringForColumn:#"fullname"];
// thisEmployee.city = [results stringForColumn:#"city"];
// thisEmployee.ste = [results stringForColumn:#"state"];
// //[employees addObject:thisEmployee];
// }
//
// [db close];
//
// return employees;
// return true;
//}
#end
Any help would be greatly appreciated.
I thought it was clear but I can see it is not. In the view class I want to be able to load an NSMutableArray called *employees that comes from the SQLLite database and out them on the screen. I have tried to centralize the code for data access in the GetEmployee class. Everything in that class deals with the data - web service, load the data to the database, and getting the data out of the database as well. So in that Class I have a method "getEmployees" that gets data from the db and loads it into that NSMutableArry. So here is the problem, in the class I cannot get access to the methods or properties in GetEmpployee. That is my question.
Without reading through all the code you've posted...
For using a Class method, the syntax is:
[ClassName methodName];
[ClassName anotherMethod:withArguments];
Methods that are called using this syntax will look like this in the corresponding .h file:
+(void)methodName;
+(void)anotherMethod:(NSNumber*)number;
For using an instance method, the syntax is:
ClassName myObj = [[ClassName alloc] init];
[myObj someMethod];
[myObj someOtherMethod:withArguments];
Methods that are called using this syntax will look like this in the corresponding .h file:
-(void)someMethod;
-(void)someOtherMethod:(NSString*)parameter;