ios - Swift:在工作日的特定时间安排本地通知

标签 ios swift uilocalnotification localnotification

您好,我正在尝试安排本地通知在工作日(周一至周五)上午 9:00 触发,但似乎找不到任何有关如何执行此操作的文档。这是到目前为止我的代码:

@IBAction func scheduleLocal(sender: UIButton) {
    guard let settings = UIApplication.sharedApplication().currentUserNotificationSettings() else { return
    }
    if settings.types == .None {
        let ac = UIAlertController(title: "Cant Schedule", message: "No Permission", preferredStyle: .Alert)
        ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
        presentViewController(ac, animated: true, completion: nil)
        return
    }
    let notification = UILocalNotification()
    notification.fireDate = NSDate()
    notification.alertBody = "Come Exercise"
    notification.alertAction = "Exercise Time"
    notification.soundName = UILocalNotificationDefaultSoundName
    notification.userInfo = ["customField1": "w00t"]
    UIApplication.sharedApplication().scheduleLocalNotification(notification)
}

在viewDidLoad中:

let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
    UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings) 

最佳答案

这是我的类示例,您可以根据需要使用它,我还通过将阿拉伯数字翻译成英语来支持阿拉伯语。

//
//  notification.swift
//  NSFetchController Pro
//
//  Created by Mr.Geeker on 08/02/15.
//  Copyright (c) 2015 X2coder. All rights reserved.
//

import UIKit

class notification {


    func createNotification(#hour:String, day:String, msgBody:String)->Bool
    {
        if(self.checkifNotificationOnOrOff())

        {



            //println("\(araToString(hour))")

            var dateFormatter:NSDateFormatter = NSDateFormatter()

            dateFormatter.locale = NSLocale.currentLocale()
            dateFormatter.dateStyle = NSDateFormatterStyle.NoStyle
            dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
            var convertedTime:String = ""

            var testDate:NSDate = NSDate()

            var timeFormat:NSString = dateFormatter.stringFromDate(testDate)

            // Get the range of date (AM OR PM )
            var amRange:NSRange = timeFormat.rangeOfString(dateFormatter.AMSymbol)
            var pmRange:NSRange = timeFormat.rangeOfString(dateFormatter.PMSymbol)

            var is24h:Bool = (amRange.location == NSNotFound && pmRange.location == NSNotFound)
            if is24h {

                araToString(hour)

            }else{

                var dateFormatter2:NSDateFormatter = NSDateFormatter()
                dateFormatter2.dateFormat = "HH:mm"

                var hourDate:NSDate = dateFormatter2.dateFromString(hour)!

                var pmAmDateString:NSString = dateFormatter2.stringFromDate(hourDate)

                convertedTime = pmAmDateString
                println(convertedTime)

            }


            var hourAndMiOnly:NSArray = convertedTime.componentsSeparatedByString(":")
            var onlyHour:Int = 0
            var onlyMinuts:Int = 0

            for var i:Int = 0; i < 2; i++ {

                for  thimes in hourAndMiOnly
                {
                    if i == 0
                    {
                        onlyMinuts = thimes.integerValue

                    }
                    if i == 1 {
                        // we should add -1 before the class
                        onlyHour = (thimes.integerValue)
                        if onlyHour < 1
                        {
                            onlyHour = 00
                        }
                        break
                    }

                }
            }


            let DaysDic = [0:"None",1:"Sunday",2 :"Monday",3 :"Tuesday",4 :"Wednesday",5 :"Thursday",6 :"Friday",7 :"Saturday"]

            var ConvertDayToInt:Int?{

                for (key,value) in DaysDic
                {
                    if value == day
                    {
                        return key
                    }

                }
                return nil
            }

            //println("Hour is \(onlyHour) And Minut \(onlyMinuts) AND Day \(ConvertDayToInt)")

            let date = NSDate()
            var userInfo: [NSObject : AnyObject]?

            var createCalender:NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
            var dateComponenet:NSDateComponents = createCalender.components(NSCalendarUnit.YearCalendarUnit | NSCalendarUnit.WeekCalendarUnit, fromDate: date)
            dateComponenet.weekday = ConvertDayToInt!
            dateComponenet.hour = onlyHour
            dateComponenet.minute = onlyMinuts


            var fireDateToRun:NSDate = createCalender.dateFromComponents(dateComponenet)!

            var notificationClass:UILocalNotification = UILocalNotification()
            notificationClass.alertBody = msgBody
            notificationClass.fireDate  = fireDateToRun
            notificationClass.soundName = UILocalNotificationDefaultSoundName
            notificationClass.repeatInterval = NSCalendarUnit.WeekCalendarUnit
            notificationClass.timeZone = NSTimeZone.defaultTimeZone()
            notificationClass.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1

            UIApplication.sharedApplication().scheduledLocalNotifications = [notificationClass]


        }else{

            // call protocol function not support notification
        }

        return true
    }



    func araToString(numericString:String)->NSString
    {
        var nsMutString:NSMutableString = NSMutableString(string: numericString)
        let ArabicString:NSString = "١٢٣٤٥٦٧٨٩:"
        let EnglishString:NSString = "123456789:"

        for ( var i:Int = 0 ;   i < ArabicString.length ;  i++)
        {

            var a:NSString = ArabicString.substringWithRange(NSMakeRange(i, 1))

            var w:NSString = EnglishString.substringWithRange(NSMakeRange(i, 1))

            nsMutString.replaceOccurrencesOfString(a, withString: w, options: NSStringCompareOptions.LiteralSearch, range:NSMakeRange(0, nsMutString.length))


        }

        return nsMutString

    }


    func deleteAll(){

        let appnoti = UIApplication.sharedApplication()
        let delArray = appnoti.scheduledLocalNotifications
        if delArray.count > 0
        {
            appnoti.cancelAllLocalNotifications()

        }

    }

    func checkifNotificationOnOrOff()->Bool
    {

        let systemVer:String = UIDevice.currentDevice().systemVersion

        var finalFloat:Float = NSString(string: systemVer).floatValue

        if finalFloat < 8 {

            return false

        }else{

            return true
        }



    }
}

关于ios - Swift:在工作日的特定时间安排本地通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35768568/

相关文章:

Swift:其中包含特殊字符(如 .)的枚举名称

swift ;使用特定图像计算 TableView 中的单元格

ios - 将 UILocalNotification 信息从 AppDelegate 传递到 View Controller

iphone - 从 html 页面获取 URL - 目标

ios - 无法在 xcode 5.1.1 中运行 iOS 7.1.2 设备

ios - “NSMutableSet”不能隐式转换为 'Set<NSObject>'

ios - 应用程序在后台运行时,UILocalNotification自定义声音的持续时间为5秒

iphone - 如何为多个值设置本地通知?

ios - 有没有办法在该对象的动画期间获取 UIImageView 位置?

iphone - 使用 UIPinchGestureRecognizer 单方向缩放 uiviews