Friday, 29 June 2018

How to implement Notification Controller with uitableview



#import <UIKit/UIKit.h>

@interface NotificationViewController : UIViewController

@end






//
//  NotificationViewController.m


#import "NotificationViewController.h"
#import "NotificationModel.h"
#import "NotificationListTableViewCell.h"
#import "NotificationDetailViewController.h"
#import "MGSwipeTableCell.h"
#import "UIImage+FontAwesome.h"
#import "MessagesViewController.h"

@interface NotificationViewController ()

{
    int iOffset;
    NSMutableArray *arrayNotifications;
    IBOutlet UITableView *tblNotifications;
    
    NSInteger iDeletedIndex ;
    BOOL bdelete;

}
@end

@implementation NotificationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    

    
    // Do any additional setup after loading the view from its nib.
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
tblNotifications.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, tblNotifications.bounds.size.width, 20)];
   
  //  tblNotifications.editing = YES;

}
-(void)viewWillAppear:(BOOL)animated
{
    
    currentNot = nil;
    

     [[[CommonFunctions sharedInstance] getAppDelegateInstance] setNavigationBarTitle:@"Notifications" showBack:YES controller:self showNotification:NO];
    
    [arrayNotifications removeAllObjects];
    iOffset = 0;
    iDeletedIndex =-1;
    
    [self getData];

    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark custom methods
-(IBAction)deleteAllNotifications:(id)sender{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"Do you want to delete all notifications?" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *YesAction = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
       
        
        [self deleteNoti:-2];
        
    }];
    
    [alertController addAction:YesAction];
    
    UIAlertAction *noAction = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        //do something when click button
        
    }];
    
    [alertController addAction:noAction];
    
    
    [self presentViewController:alertController animated:YES completion:nil];
    

    
    
}
-(void)getData
{
    
    /* "kOffset":"0",
     
     */
    
    NSMutableDictionary *dicParamters = [[NSMutableDictionary alloc]init];
    [dicParamters setObject:[NSString stringWithFormat:@"%d", iOffset] forKey:@"kOffset"];
    
    //get ranks
    WebHelper *web2 = [[WebHelper alloc]init];
    web2._webdelegate = self;
    [web2 postData:getNotifications parameters:dicParamters];
}

-(void)setNotificationData:(NSMutableArray *)arrayNotifications1
{
    if (!arrayNotifications)
    {
        arrayNotifications = [[NSMutableArray alloc]init];
    }
    
    /*
     "notificationId": "9",
     "title": "test8",
     "message": "test big Message 8",
     "event": "COM",
     "senderId": "1",
     "createdAt": "2017-10-11 08:04:27",
     "isRead": "N"
     */
    
    
    for (NSDictionary *dic in arrayNotifications1)
    {
        NotificationModel *not = [[NotificationModel alloc]init];
        not.strID = [dic valueForKey:@"notificationId"];
        if (![[dic valueForKey:@"title"] isEqual:[NSNull null]])
            not.strTitle = [dic valueForKey:@"title"];
        if (![[dic valueForKey:@"message"] isEqual:[NSNull null]])
            not.strMessage = [dic valueForKey:@"message"];
        not.bRead = [[dic valueForKey:@"isRead"] boolValue];
        not.strType = [dic valueForKey:@"event"];
      //  if([dic valueForKey:@"rankId"])
        not.strnotificationID = [dic valueForKey:@"rankId"];
        not.strCreatedAt = [dic valueForKey:@"createdAt"];
        [arrayNotifications addObject:not];
     

    }
    
    
    [tblNotifications reloadData];
    
    if (arrayNotifications.count==0)
    {
        
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"No notifications found" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        //do something when click button
        
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    [alertController addAction:okAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
    }
    
}

-(void)deleteNoti:(int)iIndex
{
    NSMutableDictionary *dicParamters = [[NSMutableDictionary alloc]init];
    bdelete = TRUE;
    iDeletedIndex = iIndex;

    if (iIndex ==-2)//delete all
        
    {
        [dicParamters setObject:@"" forKey:@"kNotificationIds"];
        [dicParamters setObject:@"Y" forKey:@"kIsDelAll"];
    }
    else
    {
        
    NotificationModel *not = [arrayNotifications objectAtIndex:iIndex];
    
    
    //  NSArray *arr = [NSArray arrayWithObjects:not.strID, nil];
    [dicParamters setObject:not.strID forKey:@"kNotificationIds"];
    [dicParamters setObject:@"N" forKey:@"kIsDelAll"];

    }
    //get ranks
    WebHelper *web2 = [[WebHelper alloc]init];
    web2._webdelegate = self;
    [web2 postData:deleteNotification parameters:dicParamters];
    
}
NotificationModel *currentNot ;
-(void)setNotificationDetails:(NotificationModel *)notification
{
   
    
    if (!notification.bRead)
    {
        currentNot = notification;
        
        
        NSMutableDictionary *dicParamters = [[NSMutableDictionary alloc]init];
        [dicParamters setObject:notification.strID forKey:@"kNotificationIds"];
        
        //get ranks
        WebHelper *web2 = [[WebHelper alloc]init];
        web2._webdelegate = self;
        [web2 postData:NotificationRead parameters:dicParamters];
        
        
    }
    
    
}
#pragma mark Web delegate methods

-(void) didFinishLoadingData:(NSString *) strWebMethod  data:(NSDictionary *)dicResponse
{
    //    NSString *strMessage = [dicResponse valueForKey:@"message"];
    //
    //    [[CommonFunctions sharedInstance] showAlertView:strMessage view:self];
    //
    
    if ([strWebMethod isEqualToString:NotificationRead])
    {
    
        
        currentNot.bRead = YES;
        
        // NSString *notificationCount = [NSString stringWithFormat:@"%@",[dicResponse valueForKey:@"notificationCount"]];
        
        NSString *notificationCount = [[CommonFunctions sharedInstance] getNSUserDefaultValue:@"notificationCount"];
        
        
        int notificationCnt = [notificationCount intValue]- 1;
        
        [[[CommonFunctions sharedInstance] getAppDelegateInstance] setNotificationCount:[NSString stringWithFormat:@"%d", notificationCnt]];
        
        [[CommonFunctions sharedInstance] saveNSUserDefaultValue:@"notificationCount" value:[NSString stringWithFormat:@"%d", notificationCnt]];
        
        
        
    }
    if ([strWebMethod isEqualToString:getNotifications])
    {
        NSString *notificationCount = [NSString stringWithFormat:@"%@",[dicResponse valueForKey:@"notificationCount"]];
        
        [[CommonFunctions sharedInstance] saveNSUserDefaultValue:@"notificationCount" value:notificationCount];
        
        
        [self setNotificationData:[dicResponse valueForKey:@"NotificationDetails"]];
        [[[CommonFunctions sharedInstance] getAppDelegateInstance] setNotificationCount:notificationCount];

    }
    if ([strWebMethod isEqualToString:deleteNotification])
    {
        bdelete = false;

        
    if (iDeletedIndex==-2) //deleet all notifications
    {
        [arrayNotifications removeAllObjects];
        [tblNotifications reloadData];
        

        // reset count
            
            [[CommonFunctions sharedInstance] saveNSUserDefaultValue:@"notificationCount" value:@"0"];
            
        [self.navigationController popViewControllerAnimated:YES];

        
    }
        if (iDeletedIndex >=0)
        {

            NotificationModel *not = [arrayNotifications objectAtIndex:iDeletedIndex];
            [arrayNotifications removeObjectAtIndex:iDeletedIndex];
          
            
          //  NSArray *arry = [[NSArray alloc]initWithObjects:[NSIndexPath indexPathForRow:0 inSection:iDeletedIndex], nil];

            [tblNotifications reloadData];
            
            

            
          

            if (!not.bRead)//if notitification not read , decrease count
            {
                NSString *notificationCount = [[CommonFunctions sharedInstance] getNSUserDefaultValue:@"notificationCount"];

                int notificationCnt = [notificationCount intValue]- 1;
                
              
                
                [[CommonFunctions sharedInstance] saveNSUserDefaultValue:@"notificationCount" value:[NSString stringWithFormat:@"%d", notificationCnt]];

            }
            
            if (arrayNotifications.count==0)
            {
                
                
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"No notifications found" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
                    //do something when click button
                    
                    [self.navigationController popViewControllerAnimated:YES];
                }];
                
                [alertController addAction:okAction];
                
                [self presentViewController:alertController animated:YES completion:nil];
                
            }
            
        }
        
        
        iDeletedIndex = -1;
        
        
     
        
        
    }
    
    
}
-(void) didFailed:(NSString *) strWebMethod  data:(NSDictionary *)dicResponse statusCode:(NSInteger )strStatusCode
{
    
    
    
    if (strStatusCode == blockedUserCode)
    {
        
        NSString *strMessage = Blocked_User_msg;
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:strMessage preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
            //do something when click button
            
            [[CommonFunctions sharedInstance] resetUserDetails];
         //   exit(0);
        }];
        
        [alertController addAction:okAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
        
        
        
    }
    else
    {
        NSString *strMessage = [dicResponse valueForKey:@"message"];
        if(strMessage.length==0)
        {
            strMessage = Request_Failed_Msg;
        }
        
        [[CommonFunctions sharedInstance] showAlertView:strMessage view:self];
    }
}

#pragma mark Tableview  methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return arrayNotifications.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    return UITableViewAutomaticDimension;
}

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel *headerView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 12)];
    
    //Put your common code here
    // lets say you need all background color to be white. do this here
    [headerView setBackgroundColor:[UIColor clearColor]];
    
    //Check the section and do section specific contents
   
    
    return headerView;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
            
    
            
            NotificationListTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"NotificationCell"];
            if (!cell)
            {
                
                [tableView registerNib:[UINib nibWithNibName:@"NotificationListTableViewCell" bundle:nil] forCellReuseIdentifier:@"NotificationCell"];
                cell = [tableView dequeueReusableCellWithIdentifier:@"NotificationCell"];
                
            }
    
    NotificationModel *not = [arrayNotifications objectAtIndex:indexPath.section];
    cell.lblTitle.text = not.strTitle;
   
    NSData *dataa = [not.strMessage dataUsingEncoding:NSUTF8StringEncoding];
    NSString *valueEmoj = [[NSString alloc] initWithData:dataa encoding:NSNonLossyASCIIStringEncoding];
    
    cell.lblMessage.text = valueEmoj;
    //cell.lblMessage.text = not.strMessage;
    NSString *dateString = not.strCreatedAt;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *dateFromString = [dateFormatter dateFromString:dateString];
    
    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
    [dateFormatter1 setDateFormat:@"dd-MM-yyyy"];
    NSString *stringDate = [dateFormatter1 stringFromDate:dateFromString];
    
    NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
    [dateFormatter2 setDateFormat:@"HH:mm a"];
    NSString *stringTime = [dateFormatter2 stringFromDate:dateFromString];
    
    cell.lblNotificationDateTime.text = stringTime;
    cell.lblDate.text = stringDate;
    
    //unread default black & gray , for read = y light gray
    if (not.bRead)
    {
        cell.lblTitle.textColor = [UIColor colorWithRed:148/255.0 green:148/255.0 blue:148/255.0 alpha:1];
        cell.lblMessage.textColor = [UIColor colorWithRed:148/255.0 green:148/255.0 blue:148/255.0 alpha:1];
        
    }
    else
    {
        cell.lblTitle.textColor = [UIColor blackColor];
        cell.lblMessage.textColor = [UIColor colorWithRed:115/255.0 green:115/255.0 blue:115/255.0 alpha:1];
        

    }
    cell.viewContainer.layer.masksToBounds = NO;
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.tag = indexPath.section;
    
    cell.delegate = self;

    return cell;
        

    
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 75.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
{
    
    NotificationModel *not = [arrayNotifications objectAtIndex:indexPath.section];
    
    if ([not.strType isEqualToString:@"RK"])
    {
        if (not.strnotificationID.length >0)
        {
            
            [self setNotificationDetails:not];
            
        MessagesViewController *message = [MessagesViewController new];
        message.strRankID = not.strnotificationID;
        [self.navigationController pushViewController:message animated:YES];
        }
    }
    else//if ([not.strType isEqualToString:@"ADMIN"])
    {
        NotificationDetailViewController *notificationDetails = [NotificationDetailViewController new];
        
        
        [self.navigationController pushViewController:notificationDetails animated:YES ];
        
        
        [notificationDetails performSelector:@selector(setNotificationDetails:) withObject:not afterDelay:0.3];
        
    }
    
    
    

}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return YES if you want the specified item to be editable.
    return NO;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
       
        [self deleteNoti:(int)indexPath.section];
        
    }
}



#pragma mark Swipe Delegate

-(BOOL) swipeTableCell:(MGSwipeTableCell*) cell canSwipe:(MGSwipeDirection) direction;
{    if (direction == MGSwipeDirectionLeftToRight)
    {
    
        return NO;
    }
    
    return YES;
}

-(NSArray*) swipeTableCell:(MGSwipeTableCell*) cell swipeButtonsForDirection:(MGSwipeDirection)direction
             swipeSettings:(MGSwipeSettings*) swipeSettings expansionSettings:(MGSwipeExpansionSettings*) expansionSettings
{
    
    swipeSettings.transition = MGSwipeTransitionBorder;
    expansionSettings.buttonIndex = 0;
    
  
    
        
        expansionSettings.fillOnTrigger = YES;
        expansionSettings.threshold = 1.1;
        
        CGFloat padding = 20;
    
    
  //  +(instancetype) buttonWithTitle:(NSString *) title icon:(UIImage*) icon backgroundColor:(UIColor *) color
    
    //icons
    UIImage *iconProfile = [UIImage imageWithIcon:@"fa-trash-o" backgroundColor:[UIColor clearColor] iconColor:[UIColor whiteColor] fontSize:24];

    MGSwipeButton * trash = [MGSwipeButton buttonWithTitle:@"" icon:iconProfile backgroundColor:[UIColor colorWithRed:1.0 green:59/255.0 blue:50/255.0 alpha:1.0] padding:padding callback:^BOOL(MGSwipeTableCell *sender) {
            
            //NSIndexPath * indexPath = [me.tableView indexPathForCell:sender];
           
            [self deleteNoti:(int)cell.tag];
            return NO; //don't autohide to improve delete animation
        }];
    
        
        return @[trash];
    
    
    
}


@end




//
//  NotificationListTableViewCell.h


#import <UIKit/UIKit.h>

#import "MGSwipeTableCell.h"


@interface IndicatorView : UIView
@property (nonatomic, strong) UIColor * indicatorColor;
@property (nonatomic, strong) UIColor * innerColor;
@end

@interface NotificationListTableViewCell : MGSwipeTableCell
@property (weak, nonatomic) IBOutlet UILabel *lblDate;

@property(nonatomic,strong) IBOutlet UILabel *lblTitle, *lblMessage;
@property(nonatomic,strong) IBOutlet UIView *viewContainer;
@property (weak, nonatomic) IBOutlet UILabel *lblNotificationDateTime;


@end





//
//  NotificationListTableViewCell.m


#import "NotificationListTableViewCell.h"
@implementation IndicatorView

-(void) drawRect:(CGRect)rect
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextAddEllipseInRect(ctx, rect);
    CGContextSetFillColor(ctx, CGColorGetComponents(_indicatorColor.CGColor));
    CGContextFillPath(ctx);
    
    if (_innerColor) {
        CGFloat innerSize = rect.size.width * 0.5;
        CGRect innerRect = CGRectMake(rect.origin.x + rect.size.width * 0.5 - innerSize * 0.5,
                                      rect.origin.y + rect.size.height * 0.5 - innerSize * 0.5,
                                      innerSize, innerSize);
        CGContextAddEllipseInRect(ctx, innerRect);
        CGContextSetFillColor(ctx, CGColorGetComponents(_innerColor.CGColor));
        CGContextFillPath(ctx);
    }
}

-(void) setIndicatorColor:(UIColor *)indicatorColor
{
    _indicatorColor = indicatorColor;
    [self setNeedsDisplay];
}

-(void) setInnerColor:(UIColor *)innerColor
{
    _innerColor = innerColor;
    [self setNeedsDisplay];
}

@end


@implementation NotificationListTableViewCell

- (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
}



//
//  NotificationModel.h


#import <Foundation/Foundation.h>

@interface NotificationModel : NSObject
@property (strong ,atomic)    NSString *strID , *strTitle , *strMessage ,*strEvent ,*strnotificationID, *strSenderID ,*strCreatedAt;

@property (nonatomic) BOOL bRead;

@end





#import "NotificationModel.h"

@implementation NotificationModel

@end

No comments:

Post a Comment

Dependency Manager in iOS

What is Dependency Management? When working in iOS, there are plenty of amazing third party libraries that we can use to save us time an...