好久沒有更新簡(jiǎn)書啦瓮恭,最近沉迷于加班,無(wú)法自拔厘熟,現(xiàn)在程序媛上線了~
一屯蹦、背景
前幾天有個(gè)需求,需要用戶點(diǎn)擊一個(gè)開啟日歷的按鈕绳姨,然后將當(dāng)前的事件和系統(tǒng)日歷綁定登澜,并且在連續(xù)的幾天的中午12點(diǎn)給用戶提醒消息,OK飘庄,廢話不多說脑蠕,上代碼
二、實(shí)現(xiàn)方式
1跪削、首先在info.plist文件中添加權(quán)限
Privacy - Calendars Usage Description 訪問日歷的權(quán)限
Privacy - Reminders Usage Description 訪問提醒事件的權(quán)限
2空郊、判斷是否有權(quán)限
class EventCalendar: NSObject {
//單例
static let eventStore = EKEventStore()
///用戶是否授權(quán)使用日歷
func isEventStatus() -> Bool {
let eventStatus = EKEventStore.authorizationStatus(for: EKEntityType.event)
if eventStatus == .denied || eventStatus == .restricted {
return false
}
return true
}
}
EventCalendar.eventStore.requestAccess(to: EKEntityType.event) { [unowned self] (granted, error) in
//用戶沒授權(quán)
if !granted {
let alertViewController = UIAlertController(title: "提示", message: "請(qǐng)?jiān)趇Phone的\"設(shè)置->隱私->日歷\"選項(xiàng)中,允許***訪問你的日歷份招。", preferredStyle: .alert)
let actionCancel = UIAlertAction(title: "取消", style: .cancel, handler: { (action) in
})
let actinSure = UIAlertAction(title: "設(shè)置", style: .default, handler: { (action) in
//跳轉(zhuǎn)到系統(tǒng)設(shè)置主頁(yè)
if let url = URL(string: UIApplicationOpenSettingsURLString) {
//根據(jù)iOS系統(tǒng)版本,分別處理
if #available(iOS 10, *) {
UIApplication.shared.open(url)
} else {
UIApplication.shared.openURL(url)
}
}
})
alertViewController.addAction(actionCancel)
alertViewController.addAction(actinSure)
self.present(alertViewController, animated: true, completion: nil)
return
}
}
3狞甚、獲取第二天中午12點(diǎn)的date
func getTomorrowDate(_ timeCount: Int, dayCount: Int) -> Date {
let calendar = NSCalendar.current
var componts = calendar.dateComponents([.weekday, .year, .month, .day], from: Date())
guard let day = componts.day else {
return Date()
}
componts.day = day + dayCount
let tomorrowInterval: TimeInterval = TimeInterval((calendar.date(from: componts)?.timeIntervalSince1970 ?? 0) + TimeInterval(timeCount * 60 * 60))
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let tomorrowDate = Date(timeIntervalSince1970: tomorrowInterval)
return tomorrowDate
}
最后附上Demo