iOS create local notifications and delete corresponding notifications, weekday notifications

Source: Internet
Author: User

The main code of this article is: Create a local notification, delete the corresponding local notification, create a weekday alarm

Directly on the code:

////VIEWCONTROLLER.M//localnsnotification////Created by wusiping on 16/1/27.//copyright©2016 year wusiping. All rights reserved.//#import "ViewController.h"#definelocal_notify_schedule_id @ "Hahahhahahhah"@interfaceViewcontroller ()@end@implementationViewcontroller- (void) viewdidload {[Super viewdidload]; //additional setup after loading the view, typically from a nib.UIButton*CREATEBTN = [[UIButton alloc]initwithframe:cgrectmake ( -, -, -, -)]; [Createbtn settitle:@"Create a notification"Forstate:uicontrolstatenormal]; CreateBtn.titleLabel.textColor=[Uicolor Blackcolor]; Createbtn.backgroundcolor=[Uicolor Lightgraycolor];    [Createbtn addtarget:self Action: @selector (Creatensnotification) forcontrolevents:uicontroleventtouchupinside];        [Self.view ADDSUBVIEW:CREATEBTN]; UIButton*CANCELBTN = [[UIButton alloc]initwithframe:cgrectmake ( -, -, -, -)]; [Cancelbtn settitle:@"Delete Notification"Forstate:uicontrolstatenormal]; CancelBtn.titleLabel.textColor=[Uicolor Blackcolor]; Cancelbtn.backgroundcolor=[Uicolor Lightgraycolor];    [Cancelbtn addtarget:self Action: @selector (Cancelnsnotification) forcontrolevents:uicontroleventtouchupinside]; [Self.view addsubview:cancelbtn];}-(NSDate *) getcurrrenttimetoss{NSDateFormatter*formatter =[[NSDateFormatter alloc]init]; [Formatter Setdateformat:@"YYYY-MM-DD HH:mm:ss"];    [Formatter DateFormat];    [NSDate Date]; return[NSDate Date]; }- (void) creatensnotification{uilocalnotification*localnotification =[[Uilocalnotification alloc] init]; if(Localnotification = =Nil) {        return; }    //set the trigger time for local notifications (if you want to trigger immediately, without setting), this is set to 20 wonderful afterLocalnotification.firedate = [NSDate datewithtimeintervalsincenow: -]; //set the time zone for local notificationsLocalnotification.timezone =[Nstimezone Defaulttimezone]; //set the contents of a notificationLocalnotification.alertbody =@"Hahhah"; //set the caption of the Notification action buttonLocalnotification.alertaction =@"View"; //set the sound of the reminder, you can add your own sound file, which is set as the default prompt soundLocalnotification.soundname =Uilocalnotificationdefaultsoundname; //set up information about the notification, this is important, you can add some of the marked content, easy to distinguish and get the notification information laterNsdictionary *dict =[nsdictionary dictionarywithobjectsandkeys:[nsnumber numberwithint:9529],@"Nfsigninkey", nil];    [Localnotification setuserinfo:dict]; //after iOS8, you need to add this registration to be authorized    if([[UIApplication sharedapplication] Respondstoselector: @selector (registerusernotificationsettings:)]) {UIUser NotificationType type= Uiusernotificationtypealert | Uiusernotificationtypebadge |Uiusernotificationtypesound; Uiusernotificationsettings*settings =[Uiusernotificationsettings Settingsfortypes:type        Categories:nil];        [[UIApplication sharedapplication] registerusernotificationsettings:settings]; //the unit that notifies the repeating prompt, which can be day, week, monthLocalnotification.repeatinterval =Nscalendarunitday; } Else {        //the unit that notifies the repeating prompt, which can be day, week, monthLocalnotification.repeatinterval =Nsdaycalendarunit; }    //trigger a notification on a specified date[[UIApplication sharedapplication] schedulelocalnotification:localnotification];}/** * Delete the current notification*/- (void) cancelnsnotification{//Manually delete notifications//Here we are going to delete the key and the custom ID that we set when we add it .Nsarray *narry=[[UIApplication sharedapplication] scheduledlocalnotifications]; Nsuinteger acount=[Narry Count]; if(acount>0)        {            //traverse to find the corresponding Nfkey and Notificationtag notifications             for(intI=0; i<acount; i++) {uilocalnotification*myuilocalnotification =[Narry objectatindex:i]; Nsdictionary*userinfo =Myuilocalnotification.userinfo; NSNumber*obj = [UserInfo objectforkey:@"Nfsigninkey"]; intmytag=[obj intvalue]; if(mytag==9529)                {                    //Delete local Notifications[[UIApplication sharedapplication] cancellocalnotification:myuilocalnotification];  Break; }            }        }}@end

You may encounter a weekday alarm clock that requires:
 if([Cycle isequal:@"Weekday"]) {//if it's a weekday alarm clockNSDate *now=select;//Current TimeNscalendar*gregorian =[Nscalendar Currentcalendar]; Nsdatecomponents*datecomps =[Gregorian Components:nsweekdaycalendarunit Fromdate:now]; Nsinteger Daycount= [Datecomps weekday]-2; NSDate*weekdaybegin=[now addtimeinterval:-daycount* -* -* -];  for(intI=0;i<5; i++) {//Create 5 notifications: Monday to FridayNSDate *now= [Weekdaybegin addtimeinterval:i* -* -* -];            [Self creatmessage:now]; }   }-(void) Creatmessage: (NSDate *)New{uilocalnotification*notification=[[Uilocalnotification alloc] init]; if(Notification!=nil && Select!=nil &&cycle.length >0&&key.intvalue==1)    {        //Trigger Notification Time//[self canceluilocalnotification];NSDate *now=New; NSLog (@"%@", now); NSDate*today =[self getcurrrenttimetoday]; BOOL Issameday=[self issameday:now date2:today]; if(Issameday = = YES) {//Special Needs: Don't care about this .//today's week X, delayed by one week trigger. For example, today is Wednesday, the alarm clock will start next Wednesday. Tomorrow is Thursday, the Thursday alarm clock will be triggered tomorrow . Now= [NSDate datewithtimeinterval: -* -* -*7Sincedate:now]; } notification.firedate=Now ; Notification.timezone=[Nstimezone Defaulttimezone]; Notification.repeatinterval=Kcfcalendarunitweek; Notification.soundname=@"ringtones. m4r"; Notification.alertbody=@"did you sign isite today? Don't forget it! "; Notification.alertaction=nslocalizedstring (@"did you sign isite today? Don't forget it! ", nil); Nsdictionary*dict =[nsdictionary dictionarywithobjectsandkeys:[nsnumber Numberwithint:9529],@"Nfsigninkey", nil];                [Notification setuserinfo:dict]; //Enable this notification[[UIApplication sharedapplication] schedulelocalnotification:notification]; }    }

iOS create local notifications and delete corresponding notifications, weekday notifications

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.