iOS 常见代码片段 二

本文介绍了一种在iOS应用中实现定时本地推送通知的方法。通过取消所有现有通知并设置新的每日提醒来确保用户不会错过重要更新。代码示例展示了如何根据当前时间安排通知并在用户点击通知时执行特定操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//取消之前所有的本地通知
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    
    //清空 icon数量
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
    
    //启动本地通知
    UILocalNotification *notification=[[UILocalNotification alloc] init];
    if (notification!=nil)
    {
        //现在的时间
        NSDate *now=[NSDate date];
        
        
        //获得系统日期
        NSCalendar  * cal=[NSCalendar  currentCalendar];
        NSUInteger  unitFlags=NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit;
        NSDateComponents * conponent= [cal components:unitFlags fromDate:now];
        NSInteger year=[conponent year];
        NSInteger month=[conponent month];
        NSInteger day=[conponent day];
        //NSString *  nsDateString= [NSString  stringWithFormat:@"%4d年%2d月%2d日",year,month,day];
        
 
        
        //获得当天的12:00  时间
        NSString  * nsStringDate12 =  [NSString  stringWithFormat:@"%d-%d-%d-%d-%d-%d",
                            year, month,day, 12, 0, 0  ];
        
        //根据时间字符串获得NSDate
        NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"YYYY-MM-dd-HH-mm-ss"];
        NSDate  * todayTwelve=[dateformatter dateFromString:nsStringDate12];
        
        //然后比较  now跟  todayTwelve那个大,如果已经过了12点,那就设置明天12点
        NSComparisonResult   dateResult =  [now  compare:todayTwelve ];
        if (dateResult ==  NSOrderedDescending  )
        {
            NSDate  *  tomorrowTwelve =  [todayTwelve  dateByAddingTimeInterval: 24 * 60 * 60];
            
            notification.fireDate =  tomorrowTwelve;
        }
        else
        {
            notification.fireDate= todayTwelve;
        }
        notification.repeatInterval = kCFCalendarUnitDay;
        notification.timeZone=[NSTimeZone defaultTimeZone];
        notification.applicationIconBadgeNumber = 1;
 
        notification.alertBody=@"今天还没上线,好多奖励没领呢";
 
        notification.alertAction = @"打开";
        [[UIApplication sharedApplication]   scheduleLocalNotification:notification];
        [notification release];
    }

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    NSLog(@"获得本地通知");
    
    
    //点击提示框的打开
    application.applicationIconBadgeNumber = 0;
    
    
}


#pragma mark  顶部当行条的创建

-(void)createHeadView

{

    UIView *navBar=[[UIView allocinitWithFrame:CGRectMake(00self.view.frame.size.width44+[UIApplication sharedApplication].statusBarFrame.size.height)];

    navBar.backgroundColor=kheader;

    [self.view addSubview:navBar];

    

    

    UILabel *lab=[[UILabel alloc]initWithFrame:CGRectMake(0,[UIApplication sharedApplication].statusBarFrame.size.heightself.view.frame.size.width44)];

    lab.text=@"发布心情";

    lab.font=f20Font;

    lab.textColor = kWhite;

    lab.textAlignment=NSTextAlignmentCenter;

    [self.view addSubview:lab];

    

    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];

    leftBtn.frame = CGRectMake(0, [UIApplication sharedApplication].statusBarFrame.size.height8040);

    [leftBtn setBackgroundImage:[UIImage imageNamed:@"返回键透明.png"] forState:UIControlStateNormal];

    [leftBtn setBackgroundImage:[UIImage imageNamed:@"返回键-按下.png"] forState:UIControlStateHighlighted];

    [leftBtn setTitleColor:[UIColor whiteColorforState:UIControlStateNormal];

    [leftBtn addTarget:self action:@selector(leftBtnClick) forControlEvents:UIControlEventTouchUpInside];

    [navBar addSubview:leftBtn];

    

    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];

    rightBtn.frame = CGRectMake(self.view.frame.size.width-60-10, [UIApplication sharedApplication].statusBarFrame.size.height+106024);

    [rightBtn setBackgroundImage:[UIImage imageNamed:@"发布.png"forState:UIControlStateNormal];

    [rightBtn setBackgroundImage:[UIImage imageNamed:@"发布-.png"forState:UIControlStateHighlighted];

    [rightBtn addTarget:self action:@selector(rightBtnClick) forControlEvents:UIControlEventTouchUpInside];

    [navBar addSubview:rightBtn];


      self.view.backgroundColor = k21;

    

}


-(void)sendReqAsync:(int) currentPage

{

    

    loading = [[LoadingView alloc]initWithFrame:CGRectMake(10064100100)];

    [loading loadingWithTrips:@"发布中···"];

    [self.view addSubview:loading];

    NSString *urlStr=[NSString stringWithFormat:myDogMoodAddUrl ,[AppDelegate instance].memberID_USER,self.feeling.text];

    urlStr = [urlStr stringByAddingPercentEscapesUsingEncodingNSUTF8StringEncoding];

    NSURL *url = [NSURL URLWithString:urlStr];

    __weak ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];

    //[request setDelegate:self];

    [request setRequestMethod:@"GET"];

    [request startAsynchronous];

    [request setCompletionBlock:^{

        NSData *responseData = [request responseData];

        NSMutableDictionary * mdic =[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:Nil];

        // NSMutableArray  *  marr=[mdic objectForKey:BODYREASON];

        if ([[mdic objectForKey:CODEREASON]isEqualToString:success100]||[[mdic objectForKey:CODEREASON]isEqualToString:maxLimit]) {

            [loading loadingSuccess];

            

            //     CircleOfFirends1ViewController * page=(CircleOfFirends1ViewController *) [self.navigationController.viewControllers objectAtIndex: ([self.navigationController.viewControllers count] -1)];

            

            

            // [self.navigationController popViewControllerAnimated:YES];

            [[NSNotificationCenter defaultCenter]postNotificationName:INTEGRAL_NUM_NOTIFY object:self];

            [[NSNotificationCenter defaultCenter]postNotificationName:BACK_HOME_PAGE_SUBVIEW1_NOTIFY object:self];//返回到主页中的子页面1

            //        [self.navigationController popToViewController: [self.navigationController.viewControllers objectAtIndex: ([self.navigationController.viewControllers count] -2)] animated:YES];

            //        [[NSNotificationCenter defaultCenter]postNotificationName:PHOTO_DIARY_FEELING_BACK_NOTIFY object:self];

            //  [self dismissViewControllerAnimated:YES completion:nil];

            [self.navigationController popViewControllerAnimated:YES];

            

        }

        


    }];

    

    [request setFailedBlock:^{

        NSError *error = [request error];

        NSLog(@"%s,%@",__FUNCTION__, error);

        [loading loadingFailed];

    }];

    

}



//消息提示

[SGInfoAlert showInfo:@"        \n最大字数不能超过150\n         "

         

                      bgColor: [UIColor orangeColor].CGColor

         

                       inView:self.view

         

                     vertical:0.3];






-(BOOL) isEmpty:(NSString *) str {

    

    if (!str) {

        return YES;

    } else {

        //A character set containing only the whitespace characters space (U+0020) and tab (U+0009) and the newline and nextline characters (U+000A–U+000D, U+0085).

        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];

        

        //Returns a new string made by removing from both ends of the receiver characters contained in a given character set.

        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];

        

        if ([trimedString length] == 0) {

            return YES;

        } else {

            return NO;

        }

    }

}


-(BOOL) isEmpty:(NSString *) str {

    

    if (!str) {

        return YES;

    } else {

        //A character set containing only the whitespace characters space (U+0020) and tab (U+0009) and the newline and nextline characters (U+000A–U+000D, U+0085).

        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];

        

        //Returns a new string made by removing from both ends of the receiver characters contained in a given character set.

        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];

        

        if ([trimedString length] == 0) {

            return YES;

        } else {

            return NO;

        }

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值