首页 > 解决方案 > IOS UserNotifications 在物理设备上的 Swift 中不起作用

问题描述

对不起,因为我是编程新手,但我已经阅读了许多其他主题,似乎找不到答案。我无法在我的物理设备上获得本地通知。我已经在模拟器中提前 5 分钟测试了它们,它们工作正常。但是当我将应用程序部署到我的手机时,它们永远不会关闭!我试过让应用程序在后台运行,将其清除,然后将其留在主视图中,什么也没有!我不确定这是否只是因为我没有付费开发人员,或者我做错了什么。请帮忙!另外,请不要取笑我可能是蹩脚的技术,但非常欢迎提出改进建议!

import UIKit
import UserNotifications
import RealmSwift

class NotificationManager {
    let realm = try! Realm()
    var prefStatus = false
    var prefDate = Date()
    struct DateStruct {
        let year: Int
        let month: Int
        let day: Int
    }
    
    struct TimeStruct {
        let hour: Int
        let minute: Int
    }
    
    
    let center = UNUserNotificationCenter.current()
//    center.delegate = self
    
    func timeUpdate() {
//        This function will be called when the preferred notification time is changed
        let center = UNUserNotificationCenter.current()
        center.getPendingNotificationRequests { (notifications) in
        center.removeAllPendingNotificationRequests()
            print("All notifications sucessfully removed")
        }
//        Use all Coupon objects to reschedule notifications
        let couponResults = realm.objects(Coupon.self)
        for coupon in couponResults {
            let title = coupon.title
            let date = coupon.expiration
            createNotification(couponTitle: title, date: date!)
        }
        print("Notification times successfully updated!")
    }
    
    
    
    func createNotification(couponTitle: String, date: Date) {
        let results = realm.objects(PreferencesList.self)
        print("Results were fetched")
        if results.count > 1 {
            if let notifTime = results[0].notificationTime {
                print("If let statement reached")
                prefStatus = true
                prefDate = notifTime
            }
        }
        let theDate = parseDate(date: date)
        let content = UNMutableNotificationContent()
                   content.title = "Expiration Alert!"
                   content.body = "Your \(couponTitle) coupon is expiring today!"
                   content.sound = UNNotificationSound.default
        //        Calender trigger that we will use
        
        var dateComponents = DateComponents()
        dateComponents.year = theDate.year
        dateComponents.month = theDate.month
        dateComponents.day = theDate.day
        dateComponents.timeZone = TimeZone.current
    
        if prefStatus {
            let theTime = parseTime(time: prefDate)
            dateComponents.hour = theTime.hour
            dateComponents.minute = theTime.minute
//            May need to add seconds as 00 if issues arise
        }
        else {
            dateComponents.hour = 9
            dateComponents.minute = 00
//            May need to add seconds as 00 if issues arise
        }
        
        print(dateComponents)
        
//        Create trigger from date components
                   
        let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
        
        
        //        Scheduling
        
//        let identifier = "UYLLocalNotification"
        let identifier = UUID().uuidString
        let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)

        center.add(request, withCompletionHandler: { (error) in
            if let error = error {
                // Something went wrong
                print("Error with notifications \(error)")
            }
            print("Notification Time")
        })
        
        
        center.getNotificationSettings { (settings) in
            if settings.authorizationStatus != .authorized {
                // Notifications not allowed
                print("Notifications are disabled")
            }
        }
    }
   
    func parseDate(date: Date) -> DateStruct {
        let calendar = Calendar.current
        let components = calendar.dateComponents([.year, .month, .day], from: date)
        let y = components.year!
        let m = components.month!
        let d = components.day!
        let dS = DateStruct(year: y, month: m, day: d)
        return dS
        
    }
    
    func parseTime(time: Date) -> TimeStruct {
        let calender = Calendar.current
        let components = calender.dateComponents([.hour, .minute], from: time)
        let h = components.hour!
        let m = components.minute!
        let tS = TimeStruct(hour: h, minute: m)
        return tS
    }
}

标签: swiftnotificationssimulator

解决方案


推荐阅读