Add a local push at a specified time in the app with Swift

Source: Internet
Author: User

Because of the project needs, so the study of a day of local push, now, write it blog, record their thoughts.

Think about it, the local push back is not difficult, mainly on the online data a lot, compared to spend time is the project logic (where to add, where to cancel, how to know whether to add, etc.).

Now to talk about how to add local push, how to cancel local push, and how to set a fixed time push (in this article is every night Nine o'clock)

To add push notifications to your app, start with the app's Appdelegate

Application (Application: uiapplication, didfinishlaunchingwithoptions launchoptions: [NSObject: anyobject]?) method to add a registration notification:

IOS8 or iOS after version registration local notification method:

Let pushtypes: uiusernotificationtype = [uiusernotificationtype. Badge,uiusernotificationtype. Alert,uiusernotificationtype. Sound]

Let mysetting: uiusernotificationsettings = uiusernotificationsettings(fortypes:pushtypes , Categories:nil)

UIApplication. Sharedapplication(). Registerusernotificationsettings(mysetting)

iOS8.0 the following registration notification methods:

UIApplication. Sharedapplication(). Registerforremotenotificationtypes([uiremotenotificationtype. Alert,uiremotenotificationtype. Badge,uiremotenotificationtype. Sound])

After registering the notification, the next step is how to add a local push and set a fixed time push:

  MARK: Add local push func addlocalnotification () {//local push time (temporarily nine o'clock) let pushtime:float = 21*60*60//Initial Initialize local notification Let lnotification = Uilocalnotification () To date = NSDate () to Dateformatter = Nsdateformat ter ()//date format "hours, minutes, seconds" Dateformatter.dateformat = "HH,MM,SS"//Device Current time (24-hour system) let Strdate = Date        Formatter.stringfromdate (date)//Divide the time, minute, and seconds into an array let Datearr = Strdate.componentsseparatedbystring (",") Unify translates into seconds let hour = ((Datearr[0] as NSString). Floatvalue) *60*60 Let minute = ((Datearr[1] as Nsstrin g). Floatvalue) *60 Let second = (datearr[2] as nsstring). floatvalue var newpushtime = Float () if hour > pushtime {newpushtime = 24*60*60-(hour+minute+second) +pushtime} else {newpushtime = P                ushtime-(Hour+minute+second)} Let Firedate = NSDate (Timeintervalsincenow:nstimeinterval (newPushTime))     Set push time   Lnotification.firedate = firedate//Set push time zone Lnotification.timezone = Nstimezone.defaulttimezone ()/ /applied Red Number Lnotification.applicationiconbadgenumber = 1//push sound Lnotification.soundname = uilocalnotific Ationdefaultsoundname//push content lnotification.alertbody = pushbody//repeat Interval lnotification.repeatint Erval = nscalendarunit.day///Add a dictionary type of info, mainly to record the identity of the notification, here with a key name let info = nsdictionary (object:cartloc        Alnotifi, Forkey:key_cartlocalnotifi) Lnotification.userinfo = info as [Nsobject:anyobject]//app Add this local notification     Uiapplication.sharedapplication (). Schedulelocalnotification (Lnotification)}

Once you've added this method, you'll be able to push your app on time at nine o'clock every night.

The next thing to say is how to detect if your app has added the local push you want to add (avoid adding it repeatedly) and remove the local push you've added (if you push it every minute, don't you feel annoying??). )

The principle of detecting whether a local push has been added is to get all the local pushes (an array) of the device first, and then you want to traverse the array to see if you have added the key name when you create the local push.

Nonsense not much to say, on the code:

Get local push array let            LocalArray = Uiapplication.sharedapplication (). scheduledlocalnotifications            if LocalArray! = Nil && LocalArray? Count > 0 {for                localnotif in localarray! {Let                    dict = Localnotif.userinfo                    if dict! = nil {let                        notifiname = dict![ Key_cartlocalnotifi] as? String                        if notifiname! = Nil && Notifiname = = Cartlocalnotifi {                            //Cancel push                            Uiapplication.sharedapplication (). Cancellocalnotification (Localnotif)}}}            

  

Cartlocalnotifi and
Key_cartlocalnotifi for convenience, I write a global variable, in fact, the string field, the former is the name of the notification, the latter is the name of the notification key.
Ah!! Finally finished ... I hope you can learn something from my blog ....

Add a local push at a specified time in the app with Swift

Related Article

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.