News feed are not shown in table viewcontroller.BuyerSocialPage that is linked with Newsfeed Viewcontroller has BuyerSocialPage.h file
#interface BuyerSocialPage : UIViewController <UITableViewDataSource,UITableViewDelegate>
#end
#implementation BuyerSocialPage
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.tableView.delegate=self;
UINib * firstNib = [UINib nibWithNibName:#"BSPFirstCell" bundle:nil];
[self.tableView registerNib:firstNib forCellReuseIdentifier:#"BSPFirstCell"];
UINib * secondNib = [UINib nibWithNibName:#"BSPSecondCell" bundle:nil];
[self.tableView registerNib:secondNib forCellReuseIdentifier:#"BSPSecondCell"];
UINib * thirdNib = [UINib nibWithNibName:#"BSPThirdCell" bundle:nil];
[self.tableView registerNib:thirdNib forCellReuseIdentifier:#"BSPThirdCell"];
UINib * fourthNib = [UINib nibWithNibName:#"BSPFourthCell" bundle:nil];
[self.tableView registerNib:fourthNib forCellReuseIdentifier:#"BSPFourthCell"];
self.view.backgroundColor = [UIColor whiteColor];
[self getBuyerSocialPage];
if (self.revealViewController) {
[_sidebarButton addTarget:self.revealViewController action:#selector(revealToggle:) forControlEvents:UIControlEventTouchUpInside];
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
}
}
-(void)getBuyerSocialPage {
}
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
int row = (int)indexPath.row;
if (row == 0) {
return 324;
}
else if (row == 1)
{
return 152;
}
else if (row == 2)
{
return 152;
}
else
{
return 152;
}
}
#end
After login you will see home screen. From side menu bar at the top select the "news feed" and it should display the news feed.but it is not displaying newsfeeds.Api is running correctly on postman
How I can get news feed in the table view ?
Page Number is missing in your url &pageno=1.
Your url looks like this:
http://api.shoclef.com/api/NewsFeed?user_id=1164
It should be like this:
http://api.shoclef.com/api/NewsFeed?user_id=1164&pageno=1
try this in you API Manager class. Working fine for me.
NSString * url = [NSString stringWithFormat:#"%#NewsFeed?user_id=%I&pageno=1",API_BASE_URL,userID];
Update For Image
Update this code in your cellForRowAtIndexPath function in NewsFeedNew class
NSString *strUrl = [self.images objectAtIndex:indexPath.row].image;
strUrl = [strUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
[cell.image sd_setImageWithURL:[NSURL URLWithString:strUrl]];
You need to set tableview delegate and dataSource.
Also put a break point in numberOfRowsInSection method to verify that tableview is set with datasource and delegate.
You need to reload data of tableview when you get response - [self.tableView reloadData];
-(void)getBuyerSocialPage {
NSLog(#"getBuyerSocialPage");
UserDao * profileID = [[DatabaseManager sharedManager]getLoggedInUser];
ApiManager * manager = [ApiManager sharedManager];
[manager socialPageWithProfileID:profileID.userID withCompletionBlock:^(BOOL error, NSDictionary *socialPage) {
// NSMutableArray * details = [[NSMutableArray alloc]init];
for (NSDictionary * temp in socialPage ) {
[self.socialPageArray addObject:temp];
}
[self.tableView reloadData];
if (!error) {
self.profileImages=self.socialPageArray;
}
}];
}
Few things to debug here,
Your API response might be nil or having error check and log appropriate response.
If the server response is correct then get on the main thread and reload the TableView
Set the UITableViewDataSource and UITableViewDelegate to self if you haven't done in storyboard.
- (void)getBuyerSocialPage {
NSLog(#"getBuyerSocialPage");
UserDao *profileID = [[DatabaseManager sharedManager] getLoggedInUser];
ApiManager *manager = [ApiManager sharedManager];
__weak BuyerSocialPage *weakSelf = self;
[manager socialPageWithProfileID:profileID.userID withCompletionBlock:^(BOOL error, NSDictionary *socialPage) { [weak self]
if (error) {
NSLog("Error fetching data");
return;
}
for (NSDictionary *temp in socialPage ) {
[weakSelf.socialPageArray addObject:temp];
}
if ([weakSelf.socialPageArray count] > 0) {
// update UI on the main thread
dispatch_async(dispatch_get_main_queue(), ^{
weakSelf.tableView.reloadData()
}
}
}]
}
Related
What is the correct way of using NSDiffableDataSourceSnapshot and - (void)tableView:(nonnull UITableView *)tableView prefetchRowsAtIndexPaths:(nonnull NSArray<NSIndexPath *> *)indexPaths.
It seems that every time prefetch reloads table view, table view asks for more prefetching, after calling apply snapshot, creating infinite loop.
- (void)reloadViews {
//[self.tableView reloadData];
NSMutableArray *items = [NSMutableArray new];
for (TCHChannel* channel in self.channels) {
[items addObject:channel.sid];
}
if ([items count] == 0) {
return;
}
NSDiffableDataSourceSnapshot<ConversationSectionType*, NSString*> *snapshot =
[[NSDiffableDataSourceSnapshot<ConversationSectionType*, NSString*> alloc] init];
ConversationSectionType *main = [ConversationSectionType new];
main.section = kMain;
[snapshot appendSectionsWithIdentifiers:#[main]];
[snapshot appendItemsWithIdentifiers:items intoSectionWithIdentifier:main];
[self.diffDataSource applySnapshot:snapshot animatingDifferences:NO];
}
And here is prefetch method:
- (void)tableView:(nonnull UITableView *)tableView prefetchRowsAtIndexPaths:(nonnull NSArray<NSIndexPath *> *)indexPaths {
for (NSIndexPath *indexPath in indexPaths) {
TCHChannel *channel = [self channelForIndexPath:indexPath];
NSMutableSet *currentChannelIds = [NSMutableSet new];
for (ConversationListViewModelUpdateOperation *op in self.modelQueue.operations) {
[currentChannelIds addObject:[op channelId]];
}
if ([currentChannelIds containsObject:channel.sid]) {
continue;
}
NSParameterAssert(channel != nil);
ConversationListViewModelUpdateOperation *op = [[ConversationListViewModelUpdateOperation alloc] initWithChannel:channel cache:self.channelViewModelsCache];
op.completionBlock = ^{
dispatch_async(dispatch_get_main_queue(), ^(void){
[self reloadViews];
});
};
[self.modelQueue addOperation:op];
}
}
Model queue is just operation queue:
- (NSOperationQueue*)modelQueue {
if (_modelQueue == nil) {
_modelQueue = [[NSOperationQueue alloc] init];
_modelQueue.maxConcurrentOperationCount = 4;
}
return _modelQueue;
}
Is there a way to use prefetching with diffable data sources without apply asking for more indexes?
EDIT:
So calling reloadData in prefetch methods makes infinite loop.. According to https://andreygordeev.com/2017/02/20/uitableview-prefetching/
WARNING: do not call tableView.reloadData() or
tableView.reloadRows(...) from tableView(_ tableView: UITableView,
prefetchRowsAt indexPaths: [IndexPath]) method! These methods provoke
UITableView to call prefetchRowsAt... and thus lead to infinity loop.
Soo.. how has Apple intended for prefetching to be used with Diffable Data Sources? ... -.-
As my title indicated, I want to know if there's a iCarousel delegate method as well as property that I can use to set display time for each item for my banner view when auto-scroll.
Previously, I used SDCycleScrollView for my banner view and I did it this way below:
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didScrollToIndex:(NSInteger)index {
BannerData *data = self.bannerDatas[index];
NSLog(#"***************cycleScrollView************************");
NSLog(#"index --> %ld", (long)index);
NSLog(#"banner data --> %#", data);
NSLog(#"banner data duration --> %d", data.duration);
cycleScrollView.autoScrollTimeInterval = data.duration;
}
data.duration is duration for each item to stay still.
How can I achieve this with iCarousel? Thanks in advance.
Here below are my iCarousel methods so far:
- (NSInteger)numberOfItemsInCarousel:(__unused iCarousel *)carousel
{
NSLog(#">>>>>>>>>number of items in Carousel --> %lu", (unsigned long)[self.bannerDatas count]);
return (NSInteger)[self.bannerDatas count];
}
- (UIView *)carousel:(__unused iCarousel *)carousel viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view
{
view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 520, 375)];
NSLog(#"url --> %#", [NSURL URLWithString:[self.netImages objectAtIndex:index]]);
[((UIImageView *)view)sd_setImageWithURL:[NSURL URLWithString:[self.netImages objectAtIndex:index]] placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
view.contentMode = UIViewContentModeCenter;
return view;
}
- (void)scrollToItemAtIndex:(NSInteger)index duration:(NSTimeInterval)duration
{
BannerData *data = self.bannerDatas[index];
NSLog(#"***************cycleScrollView************************");
NSLog(#"index --> %ld", (long)index);
NSLog(#"banner data --> %#", data);
NSLog(#"banner data duration --> %d", data.duration);
}
- (CGFloat)carousel:(__unused iCarousel *)carousel valueForOption:(iCarouselOption)option withDefault:(CGFloat)value
{
//customize carousel display
switch (option)
{
case iCarouselOptionWrap:
{
//normally you would hard-code this to YES or NO
return YES;
}
case iCarouselOptionSpacing:
{
//add a bit of spacing between the item views
//return value * 1.05;
}
case iCarouselOptionFadeMax:
{
// if (self.carousel.type == iCarouselTypeCustom)
// {
// //set opacity based on distance from camera
// return 0.0;
// }
// return value;
}
case iCarouselOptionShowBackfaces:
case iCarouselOptionRadius:
case iCarouselOptionAngle:
case iCarouselOptionArc:
case iCarouselOptionTilt:
case iCarouselOptionCount:
case iCarouselOptionFadeMin:
case iCarouselOptionFadeMinAlpha:
case iCarouselOptionFadeRange:
case iCarouselOptionOffsetMultiplier:
case iCarouselOptionVisibleItems:
{
return value;
}
}
}
#pragma mark -
#pragma mark iCarousel taps
- (void)carousel:(__unused iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index
{
BannerData *data = self.bannerDatas[index];
if (![data.playlistId isEqualToString:#""]) { //Play Playlist
CategoryDetailData *detailData = [[CategoryDetailData alloc]init];
detailData.categoryId = data.playlistId;
RandomSecondVC *vc = [self.storyboard instantiateViewControllerWithIdentifier:#"RandomSecondVC"];
vc.detailData = detailData;
NSLog(#"vc.detailData.categoryId --> %#", vc.detailData.categoryId );
vc.hidesBottomBarWhenPushed = YES; //????sanit
[self.navigationController pushViewController:vc animated:YES];
} else if (![data.url isEqualToString:#""]) { //Show webview
WebViewVC *vc = [self.storyboard instantiateViewControllerWithIdentifier:#"WebViewVC"];
vc.hidesBottomBarWhenPushed = YES;
vc.navTitle = #"";
vc.urlString = data.url;
[self.navigationController pushViewController:vc animated:YES];
}else if (![data.videoId isEqualToString:#""]) { //Play video
VideoDetailVC *detailView = [self.storyboard instantiateViewControllerWithIdentifier:#"VideoDetailVC"];
detailView.videoId = data.videoId;
detailView.hidesBottomBarWhenPushed = YES; //????sanit
[self.navigationController pushViewController:detailView animated:YES];
}
}
Here below is how I place my Carousel view:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *tableCell = nil;
if (indexPath.section == 0) { //for banner
//++++++++++++++++++++??sanit iCarousel ver.1++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
NSLog(#"first section!!!!!!!!");
static NSString *BannerCellIdentifier = #"BannerTableViewCell"; //original
BannerTableViewCell *bannerCell = [tableView dequeueReusableCellWithIdentifier:BannerCellIdentifier]; //original
//BannerTableViewCell *bannerCell = [[BannerTableViewCell alloc]init];
[self setUpNetImages];
bannerCell.carouselView.type = iCarouselTypeCoverFlow2;
//bannerCell.carouselView.type = iCarouselTypeLinear;
//bannerCell.carouselView.autoscroll = 1; //?????sanit set autoscroll
bannerCell.carouselView.delegate = self;
bannerCell.carouselView.dataSource =self;
//??????sanit to fix banner timing issue first banner
//BannerData *data0 = self.bannerDatas[1]; //???santi
//self.cycleScrollView.autoScrollTimeInterval = data0.duration; // use this to fix timing issue of first slide
//[bannerCell.carouselView scrollToItemAtIndex:0 duration:data0.duration];
//bannerCell.carouselView.autoscroll = 0.8;
//[bannerCell.carouselView scrollToItemAtIndex:0 duration:5];
//[bannerCell.carouselView scrollToItemAtIndex:1 animated:YES];
[bannerCell.carouselView reloadData];
tableCell = bannerCell;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=//
} else { //for collection cell below
NSLog(#"not first section!!!!!!!! %d",(int)indexPath.section);
static NSString *MainHeaderCellIdentifier = #"MainHeaderTableViewCell";
MainHeaderTableViewCell *mainHeaderCell = (MainHeaderTableViewCell *)[tableView dequeueReusableCellWithIdentifier:MainHeaderCellIdentifier]; //original
mainHeaderCell.collectionView = (UICollectionView *)[mainHeaderCell viewWithTag:100];
mainHeaderCell.collectionView.delegate = self;
mainHeaderCell.collectionView.dataSource = self;
//NSLog(#"mainHeaderCell.index = %d",(int)mainHeaderCell.index);
//original
if (mainHeaderCell.collectionView == nil) {
NSLog(#"CollectionView Nil!!!!!!!");
}
tableCell = mainHeaderCell;
}
return tableCell;
}
Seems that iCarousel does not have that option, but, luckily, you can implement such functionality by yourself:
#property (nonatomic, strong) NSMutableDictionary *operations;
#property (nonatomic) BOOL isDragging;
- (void) carouselDidEndScrollingAnimation:(iCarousel *)carousel
{
if (!self.isDragging){
NSNumber *tag = #(carousel.tag);
[self.operations[tag] cancel];
self.operations[tag] = [NSBlockOperation blockOperationWithBlock:^{
double duration = [self durationForItemAtIndex:carousel.currentItemIndex inCarousel:carousel];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSInteger i = carousel.currentItemIndex + 1;
NSInteger next = i < carousel.numberOfItems ? i : 0;
[carousel scrollToItemAtIndex:next animated:YES];
});
}];
[(NSOperation*)(self.operations[tag]) start];
}
}
- (void) carouselWillBeginDragging:(iCarousel *)carousel
{
[self.operations[#(carousel.tag)] cancel];
self.isDragging = YES;
}
- (void) carouselDidEndDragging:(iCarousel *)carousel willDecelerate: (BOOL)decelerate
{
self.isDragging = NO;
}
- (double) durationForItemAtIndex:(NSInteger)index inCarousel:(iCarousel*)carousel
{
return <appropriate_duration_for_particular_carousel_and_item_index_in_it>;
}
- (void) startCarousel:(iCarousel*)carousel
{
[self carouselDidEndScrollingAnimation:carousel];
}
Update -[tableView:cellForRowAtIndexPath:] method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
<...>
if (indexPath.section == 0) {
<...>
bannerCell.carouselView.tag = indexPath.row;
[self startCarousel:bannerCell.carouselView];
} else {
<...>
}
return tableCell;
}
And don't forget to initialize the operations dictionary somewhere before usage:
self.operations = [NSMutableDictionary new];
However, all this is kind of draft - you may want to tune and upgrade these snippets according to your needs.
I'm facing problem with saving UITableViewCell's state and can't figure out how to solve it. Hope somebody can help me.
Explanation:
There is an API on server and I get data from it and then store it inside NSMutableArray. Each object of an array contains property ready which can be 1 or 0. So I've no problems with populating UITableView with this data but not every data object is ready (i.e 0) and I need to get progress of completion at server and after that to show it in each cell is need it. I've UIProgressView in dynamic prototype of UITableViewCell and set progress after getting. There is no problem if such "not ready" object is only one. But if there are many objects I can't show progress and I don't understand why.
So here is my code.
cellForRowAtIndexPath method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"readyCell";
AVMMovieCell *cell = [self.readyTable dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
if (cell == nil) {
cell = (AVMMovieCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
}
AVMFilmsStore *oneItem;
oneItem = [readyArray objectAtIndex:indexPath.row];
NSNumber *rowNsNum = [NSNumber numberWithUnsignedInt:(unsigned int)indexPath.row];
if (oneItem.ready==1){
cell.progressLabel.hidden = YES;
cell.progressLine.hidden = YES;
if ([selecedCellsArray containsObject:[NSString stringWithFormat:#"%#",rowNsNum]] )
{
if (![cell.progressLabel.text isEqualToString:#""]&& ![cell.progressLabel.text isEqualToString:#"Success"] && ![cell.progressLabel.text isEqualToString:#"Creating"]){
cell.progressLabel.hidden = NO;
cell.progressLine.hidden = NO;
} else {
cell.progressLabel.hidden = YES;
cell.progressLine.hidden = YES;
}
}
else{
if(!oneItem.isProcessing && !cell.selected){
cell.progressLabel.hidden = YES;
cell.progressLine.hidden = YES;
}
}
} else { //if processing
if (![processingCellsArray containsObject:[NSString stringWithFormat:#"%#",rowNsNum]]){
[processingCellsArray addObject:[NSString stringWithFormat:#"%#",rowNsNum]];
if (!cell.isSelected){
[cell setSelected:YES];
}
cell.progressLabel.hidden = NO;
cell.progressLine.hidden = NO;
NSArray * arrayOfThingsIWantToPassAlong =
[NSArray arrayWithObjects: cell, oneItem, indexPath, nil];
if(!isMaking){
[self performSelector:#selector(getProgress:)
withObject:arrayOfThingsIWantToPassAlong
afterDelay:0];
} else{
[self performSelector:#selector(getProgress:)
withObject:arrayOfThingsIWantToPassAlong
afterDelay:0.5];
}
isMaking = YES;
} else {
if (!cell.isSelected){
[cell setSelected:YES];
}
cell.progressLabel.hidden = NO;
cell.progressLine.hidden = NO;
NSArray * arrayOfThingsIWantToPassAlong =
[NSArray arrayWithObjects: cell, oneItem, indexPath, nil];
if(!isMaking){
[self performSelector:#selector(getProgress:)
withObject:arrayOfThingsIWantToPassAlong
afterDelay:0];
} else{
[self performSelector:#selector(getProgress:)
withObject:arrayOfThingsIWantToPassAlong
afterDelay:0.3];
}
isMaking = YES;
}
}
return cell;
}
and getProgress method:
-(void)getProgress:(NSArray*)args{
if (progManager == nil && !progStop){
__block AVMFilmsStore * oneItem = args[1];
if(!oneItem.isLocal){
__block AVMMovieCell * cell = args[0];
__block NSIndexPath *indexPath = args[2];
progManager = [AFHTTPRequestOperationManager manager];
__block NSString *token = [defaults objectForKey:#"token"];
__block NSString *header = [NSString stringWithFormat:#"Bearer %#",token];
__block NSDictionary *params = #{#"lang": NSLocalizedString(#"lang",nil),#"project":oneItem.fileId};
__block NSString *oneHundredPercent;
__block NSString *progIsText;
progManager.responseSerializer = [AFJSONResponseSerializer serializer];
[progManager.requestSerializer setValue:header forHTTPHeaderField:#"Authorization"];
if(cell.selected || isMaking) { //if I just check for "cell.selected" is always "NO"
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
[progManager POST:#"http://example.com/api/project/get-progress" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
if ([[responseObject objectForKey:#"result"]isEqualToString:#"success"]){
progCreate = [responseObject objectForKey:#"progress"];
oneHundredPercent = #"100";
if ([progCreate intValue]==[oneHundredPercent intValue]){
if([processingCellsArray containsObject:[NSString stringWithFormat:#"%ld",(long)indexPath.row]]){
[processingCellsArray removeObject:[NSString stringWithFormat:#"%ld",(long)indexPath.row]];
[cell setSelected:NO];
}
[readyArray removeAllObjects];
[defaults setObject:#"false" forKey:#"isSomethingInSort"];
isMaking = NO;
[self getReadyMovies:progIsText nameLabel:oneItem.fileName];
} else{
if([progCreate intValue]>=50){
if([progCreate intValue]>=60){
self.navigationController.navigationItem.leftBarButtonItem.enabled = YES;
createMainButton.enabled = YES;
}
[[NSNotificationCenter defaultCenter] postNotificationName:#"gotFiftyNote" object:#"50"];
[cell.progressLine setProgress:[progCreate floatValue]/100 animated:YES];
} else {
[cell.progressLine setProgress:progUploadLimit];
}
progManager = nil;
progManager.responseSerializer = nil;
progManager.requestSerializer = nil;
token = nil;
header = nil;
params = nil;
progIsText = nil;
oneItem = nil;
cell = nil;
indexPath = nil;
isMaking = YES;
progCreate = nil;
oneHundredPercent = nil;
[self getProgress:args];
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
NSLog(#"Error: %#", error.localizedDescription);
}];
}
}
}
}
Any suggestions will be helpful for me. I've a headache for two weeks with this problem.
I see your code but is kind of difficult to follow with those large methods. I wouldn't keep track of the processing cells in an array. Each cell has an object to represent, those object have a bool value of ready and a progress value, right?. So try something like this:
Make sure each of your cells have a progressView as a subview.
Your cell class should have a public method named styleForReady:(bool)isReady andProgress:(nsinteger)progress
Make the service call to see if they are done or not, for each model. Whenever that service call comes back, you just update the model objects in the array, and after they have the new progress values you do [self.tableView reloadData]. This would trigger numberOfRows (which should return arrayOfObjects.count) and cellForRowAtIndexPath:(which should dequeue the cell for that indexPath, grab the model representing that cell, something like arrayOfObjects[indexPath.row], and finally, call the cell to style itself based on that model doing [cell styleForReady:objectModel.ready andProgress:objectModel.progress])
Keep in mind that the controller should just keep track of the model objects, dequeue the cell and tell the cell to style passing the model. Don't put all the logic in the controller.
I am using the LeveyPopListView.
Inside the LeveyPopList View is a table containing jobs in a specific company. All is fine until I tap a job in the pop up list view and I've checked everything.
Here's my code:
NSArray* ar_filter=(NSArray*)[self.FilterDictionary objectForKey:#"sub_slots"];
NSInteger numberOfJobs = [[[[[self.FilterDictionary objectForKey:#"sub_slots"] valueForKey:#"company_group"] valueForKey:#"job_count"] objectAtIndex:[self.jobsTableView indexPathForSelectedRow].row] intValue];
NSLog(#"NUMBER OF JOBS: %ld", (long)numberOfJobs);
NSLog(#"ARRAY FILTER: %#", ar_filter);
//MARK: for consolidated view
if([[ar_filter objectAtIndex:[self.jobsTableView indexPathForSelectedRow].row] objectForKey:#"company_group"])
{
if(numberOfJobs > 1)
{
NSString *company_id = [[[[self.FilterDictionary objectForKey:#"sub_slots"] valueForKey:#"company_group"] valueForKey:#"company_id"] objectAtIndex:[self.jobsTableView indexPathForSelectedRow].row];
NSString *company_name = [[[[self.FilterDictionary objectForKey:#"sub_slots"] valueForKey:#"company_group"] valueForKey:#"company_name"] objectAtIndex:[self.jobsTableView indexPathForSelectedRow].row];
NSDictionary *specificCompany = [NSDictionary dictionaryWithObjectsAndKeys:company_id,#"company_id", nil];
if(specificCompany.count>0)
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:specificCompany
options:0
error:&error];
if (! jsonData)
{
NSLog(#"Got an error: %#", error);
}
else
{
strJsonStringFilter = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
}
allJobsDictionary = [NSJSONSerialization JSONObjectWithData:[network getData:[NSString stringWithFormat:#"get_all_job_offers?pt_id=%#&filter=%#",[[NSUserDefaults standardUserDefaults] objectForKey:#"pt_id"], strJsonStringFilter]] options:kNilOptions error:nil];
//this contains the jobs that are given by allJobsDictionary
jobsToDisplay=(NSArray*)[allJobsDictionary objectForKey:#"sub_slots"];
//call LeveyPopListView
LeveyPopListView *lplv = [[LeveyPopListView alloc] initWithTitle:company_name options:jobsToDisplay handler:^(NSInteger anIndex)
{
}];
lplv.delegate = self;
[lplv showInView:self.view animated:YES];
strJsonStringFilter = #"";
}
}
- (void)leveyPopListView:(LeveyPopListView *)popListView didSelectedIndex:(NSInteger)anIndex {
NSDictionary *job = (NSDictionary*)[jobsToDisplay objectAtIndex:anIndex];
// Pass data and transit to detail job view controller
[self.parentViewController performSelector:#selector(showJobDetailWith:) withObject:job];
}
-(void)showJobDetailWith:(NSDictionary *)dictionary {
// Pass data to global variable for prepareForSegue method
mapPinSelectedDictionary = dictionary;
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
MTJobDetailTableViewController *smsController=[storyboard instantiateViewControllerWithIdentifier:#"MTJobDetailTableViewController"];
[smsController setJobDetailDict:mapPinSelectedDictionary];
[self.navigationController pushViewController:smsController animated:YES];
}
from LeveyPopListVIew.m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
// tell the delegate the selection
if ([_delegate respondsToSelector:#selector(leveyPopListView:didSelectedIndex:)])
[_delegate leveyPopListView:self didSelectedIndex:[indexPath row]];
if (_handlerBlock)
_handlerBlock(indexPath.row);
// dismiss self
[self fadeOut];
}
The app crashes when this line of code:
[self.parentViewController performSelector:#selector(showJobDetailWith:) withObject:job];
is called. Can anyone help me this. Thank you.
try this
- (void)leveyPopListView:(LeveyPopListView *)popListView didSelectedIndex:(NSInteger)anIndex {
NSDictionary *job = (NSDictionary*)[jobsToDisplay objectAtIndex:anIndex];
// Pass data and transit to detail job view controller
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
MTJobDetailTableViewController *smsController=[storyboard instantiateViewControllerWithIdentifier:#"MTJobDetailTableViewController"];
[smsController setJobDetailDict: job];
[self.navigationController pushViewController:smsController animated:YES];
}
I'm having a tableview. And in my didselectrow I get the right object that I want to pass to the next controller.
This is my code:
id<NavigateDelegate> strongDelegate = self.delegate;
NSDictionary * dictionary = [_dataArray objectAtIndex:indexPath.section];
NSArray * array = [dictionary objectForKey:#"data"];
POI * poi = [array objectAtIndex:indexPath.row];
NSLog(#"%#", poi);
NSLog(#"Category %#", poi.rank.name);
[tableView deselectRowAtIndexPath:indexPath animated:YES];
DetailsViewController * detailsController = [[DetailsViewController alloc] init];
detailsController.details = [[NSDictionary alloc] initWithObjectsAndKeys:poi.name, #"name", poi.address, #"address", poi.details, #"details", poi.title, #"title", poi.url, #"url", nil];
if ([strongDelegate respondsToSelector:#selector(navigateFromTo:to:)]) {
[strongDelegate navigateFromTo:self to:detailsController];
}
Then in my delegate receiver I push the controller like:
- (void) navigateFromTo:(POITableViewController *)viewController to:(UIViewController *)toController
{
[self.navigationController pushViewController:toController animated:YES];
}
But still my DetailsController his details NSdictionary is null.
What am I doing wrong?
I found the problem. The viewdid load is called before my setter is called.
So I changed the init method like this:
-(instancetype) initWithPoi:(NSDictionary *) poi
{
self = [super init];
if(self)
{
NSLog(#"Init DetailsViewController");
_details = poi;
[self initializeViews];
}
return self;
}
that way the controller has the poi details from the start.