iOS 10 UNNotificationAction发送电子邮件/短信

时间:2016-09-20 16:05:24

标签: ios swift notifications

我正在尝试使用UNNotification操作来允许用户向其他人发送电子邮件/短信“警报”(即委托操作)。当我点击通知本身时,它会进入前台,我可以转到右侧屏幕并查看“警报”而不会出现问题。

我添加了三个自定义操作(查看/电子邮件/发送短信,视图有点多余,但我希望他们在这里知道所有选项)。正确调用我的委托方法userNotificationCenter(_:didReceive:withCompletionHandler)没问题。但是,应用程序没有出现在前台。我想提出一个MFMailComposeViewController / MFMessageComposeViewController来处理这个动作。如果我在警报到达时处于前台,一切都很完美。但是,如果我在警报到达时处于后台,则应用程序将保留在后台,并且MFMailComposeViewController / MFMessageComposeViewController视图不会出现。

有办法解决这个问题吗?

以下是我AppDelegate的一些代码

static let VIEW_IDENTIFIER = "VIEW_IDENTIFIER"
static let EMAIL_IDENTIFIER = "EMAIL_IDENTIFIER"
static let SMS_IDENTIFIER = "SMS_IDENTIFIER"
static let ALERT_CATEGORY_IDENTIFIER = "ALERT_CATEGORY_IDENTIFIER"

if #available(iOS 10.0, *) {
        print("registerForPushNotification(iOS10)")
        let unViewAction = UNNotificationAction(identifier: AppDelegate.VIEW_IDENTIFIER, title: "View".localized())
        let unEMailAction = UNNotificationAction(identifier: AppDelegate.EMAIL_IDENTIFIER, title: "EMail".localized())
        let unSMSAction = UNNotificationAction(identifier: AppDelegate.SMS_IDENTIFIER, title: "SMS".localized())

        let unAlertCategory = UNNotificationCategory(identifier: AppDelegate.ALERT_CATEGORY_IDENTIFIER, actions: [unViewAction, unEMailAction, unSMSAction], intentIdentifiers: [], options: [.customDismissAction])

        let center = UNUserNotificationCenter.current()
        center.delegate = self
        center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
            // Enable or disable features based on authorization.
            print("center.requestAuthorization granted(\(granted)) error(\(error))")
        }
        center.setNotificationCategories([unAlertCategory])
        application.registerForRemoteNotifications()
    }

@available(iOS 10.0, *)
public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Swift.Void) {
    let notification = response.notification
    print("userNotificationCenter:didReceive(\(response.actionIdentifier), \(notification.debugDescription))")
    doCustomAction(identifier: response.actionIdentifier, userInfo: notification.request.content.userInfo)
    completionHandler()
}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Swift.Void) {
    print("userNotificationCenter:willPresent(\(notification.debugDescription))")
    completionHandler([.alert, .sound])
}

func doCustomAction(identifier: String, userInfo: [AnyHashable : Any]) {
    if identifier == AppDelegate.SMS_IDENTIFIER || identifier == AppDelegate.EMAIL_IDENTIFIER {
        if let current = TitanTabBarController.currentViewController {
            let json = JSON(userInfo)
            let alertJSON = json["Alert"]
            if alertJSON.type != .null {
                let credentials = Credentials(ip: json["serverIP"].stringValue, type: json["serverType"].stringValue == "Switch" ? .switch : .server)
                let alert = Alert(credentials: credentials, json: alertJSON)
                let msg = Alert.FullMessage([alert])
                if identifier == AppDelegate.SMS_IDENTIFIER {
                    current.sendMessage(message: msg)
                }
                if identifier == AppDelegate.EMAIL_IDENTIFIER {
                    current.sendMessage(message: msg)
                }
            }
        }
    } else  {
        AppEventManager.instance.post(event: .notificationAction, sender: self, data: userInfo)
    }
}

这是我用于MFMailComposeViewController的扩展代码

extension UIViewController: MFMailComposeViewControllerDelegate {
func sendEMail(message: String) {
    print(message)
    if MFMailComposeViewController.canSendMail() {
        let mail = MFMailComposeViewController()
        mail.mailComposeDelegate = self
        mail.setSubject("APCON Mobile Alert".localized())
        mail.setMessageBody(message, isHTML: false)

        present(mail, animated: true) {
            print("MFMailComposeViewControllerDelegate controller.present completion")
        }
    } else {
        showToast(msg: "Mail is not currently available on this device".localized())
    }
}
public func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
    switch (result) {
    case .cancelled:
        print("Message was cancelled")
    case .saved:
        print("Message was saved")
    case .sent:
        print("Message was sent")
    case .failed:
        print("Message failed")
        showToast(msg: "Sending text message failed".localized())
    }
    dismiss(animated: true, completion: nil)
}

这是我用于MFMessageComposeViewControllerDelegate

的扩展代码
extension UIViewController: MFMessageComposeViewControllerDelegate {
func sendMessage(message: String) {
    print(message)
    if MFMessageComposeViewController.canSendText() {
        let msg = MFMessageComposeViewController()
        msg.messageComposeDelegate = self
        msg.body = message

        present(msg, animated: true)  {
            print("MFMessageComposeViewControllerDelegate controller.present completion")
        }
    } else {
        showToast(msg: "Texting is not currently available on this device".localized())
    }
}

public func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
    switch (result) {
    case .cancelled:
        print("Message was cancelled")
    case .failed:
        print("Message failed")
        showToast(msg: "Sending text message failed".localized())
    case .sent:
        print("Message was sent")
    }
    dismiss(animated: true, completion: nil)
}

}

我没有包含showToast方法/ AppEventManager类来节省空间。

提前感谢您提供任何帮助

1 个答案:

答案 0 :(得分:3)

好吧,我现在觉得很傻。昨天我花了几个小时寻找答案而没有找到答案。发布问题5分钟后,我找到了一个非常简单的答案。只需在UNNotificationAction初始化程序中添加.foreground选项,如下所示。

            let unViewAction = UNNotificationAction(identifier: AppDelegate.VIEW_IDENTIFIER, title: "View".localized(), options: [.foreground])
        let unEMailAction = UNNotificationAction(identifier: AppDelegate.EMAIL_IDENTIFIER, title: "EMail".localized(), options: [.foreground])
        let unSMSAction = UNNotificationAction(identifier: AppDelegate.SMS_IDENTIFIER, title: "SMS".localized(), options: [.foreground])