【问题标题】:'UNLocationNotificationTrigger' is not available in Mac Catalyst“UNLocationNotificationTrigger”在 Mac Catalyst 中不可用
【发布时间】:2020-07-20 18:03:47
【问题描述】:

我正在尝试通过 Catalyst 将应用程序移植到 MacOS,但我立即遇到了障碍。

UNLocationNotificationTrigger 在 MacOS 中不可用是完全有意义的。您不会在笔记本电脑打开导航的情况下四处游荡。但是,无论我用@available(iOS 13.0, *)#if !(TARGET_OS_MACCATALYST) ... #endif 封装类,它都不会构建。

这是该类的代码:

import CoreLocation
import UserNotifications

@available(iOS 13.0, *)
class NotificationManager {
    
    // MARK: Shared Instance
    static let session = NotificationManager()
    
    // MARK: Initialisers
    init() {
        self.askForNotificationPermissions()
    }
    
    // MARK: Properties
    var isPermitted: Bool = false
    
    // MARK: Start Route Methods
    public func addStationStartNotification(for stations: [Stations.Station]) {
        guard UserLocation.current.isPermitted && self.isPermitted else { return }
        
        for station in stations {
            let region = CLCircularRegion(center: station.coordinates(), radius: 50, identifier: station.name)
            region.notifyOnEntry = true
            region.notifyOnExit = false
            
            let content = self.createStationStartContent(for: station)
            let startJourneyAction = UNNotificationAction(identifier: "Start Journey", title: "Start Journey", options: .foreground)
            
            #if !(TARGET_OS_MACCATALYST)
                let trigger = UNLocationNotificationTrigger(region: region, repeats: true)
            #endif
            
            let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
            let category = UNNotificationCategory(identifier: "Start Journey", actions: [startJourneyAction], intentIdentifiers: [], hiddenPreviewsBodyPlaceholder: "", options: .customDismissAction)
            
            self.addNotification(request)
            self.addCategory(category)
        }
    }
    
    private func createStationStartContent(for station: Stations.Station) -> UNNotificationContent {
        let notification = UNMutableNotificationContent()
        
        notification.title = "Start a Journey?"
        notification.body = "It looks like you're near \(station.name) station."
        notification.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "Resources/Alert Tones/alert_tone.caf"))
        notification.categoryIdentifier = "Start Journey"
        
        return notification
    }
    
}

extension NotificationManager {
    
    private func askForNotificationPermissions() {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (authorized, error) in
            if error != nil {
                self.isPermitted = false
            } else {
                self.isPermitted = authorized
            }
        }
    }
    
    private func addNotification(_ notification: UNNotificationRequest) {
        let center = UNUserNotificationCenter.current()
        
        center.removeAllPendingNotificationRequests()
        center.removeAllDeliveredNotifications()
        center.getPendingNotificationRequests { (pendingNotifications) in
            if !pendingNotifications.contains(where: {$0.content.title == notification.content.title && $0.content.body == notification.content.body}) {
                center.add(notification) { (error) in
                    if let error = error {
                        fatalError(error.localizedDescription)
                    }
                }
            }
            
            pendingNotifications.forEach({print("[NotificationManager] Pending Notification: \($0.content.title) - \($0.content.body)")})
        }
    }
    
    private func addCategory(_ category: UNNotificationCategory) {
        let center = UNUserNotificationCenter.current()
        
        center.getNotificationCategories { (categories) in
            if !categories.contains(category) {
                var newCategories = categories
                newCategories.insert(category)
                
                center.setNotificationCategories(newCategories)
            }
        }
    }
    
    private func removeNotification(title: String = "", body: String = "") {
        let center = UNUserNotificationCenter.current()
        center.getPendingNotificationRequests { (pendingNotifications) in
            let notificationsToRemove = pendingNotifications.filter({$0.content.title == title && $0.content.body == body}).map({$0.identifier})
            center.removePendingNotificationRequests(withIdentifiers: notificationsToRemove)
        }
    }
    
}

【问题讨论】:

    标签: ios swift macos core-location mac-catalyst


    【解决方案1】:

    用条件换行是不够的,您还应该对依赖于该行的每段代码都这样做。

    例如,在这里创建请求时不能使用变量trigger,因为编译器看不到该变量的定义位置:

    #if !(TARGET_OS_MACCATALYST)
    let trigger = UNLocationNotificationTrigger(region: region, repeats: true)
    #endif
                
    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
    

    附:我更喜欢使用#if !targetEnvironment(macCatalyst) 而不是#if !(TARGET_OS_MACCATALYST),因为前者是后者的Swifty version

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-19
      • 2020-02-05
      • 1970-01-01
      • 2020-10-28
      • 1970-01-01
      相关资源
      最近更新 更多