如何使用 swift 3 通过 firebase 推送通知发送图像

2024-03-29

任何人都可以帮我发送这样的通知:

我正在使用 Firebase 通知。当我发送通知时,我尝试将图像 URL 放入高级选项和键 1 的值中。图像 URL 显示在调试器中,但当我的设备中出现通知时,没有显示图像。

这是我的代码。

import UIKit
import UserNotifications
import Firebase
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"

func application(_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    // Register for remote notifications. This shows a permission dialog on first run, to
    // show the dialog at a more appropriate time move this registration accordingly.
    // [START register_for_notifications]
    if #available(iOS 10.0, *) {
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })

        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self
        // For iOS 10 data message (sent via FCM)
        FIRMessaging.messaging().remoteMessageDelegate = self

    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }

    application.registerForRemoteNotifications()

    // [END register_for_notifications]
    FIRApp.configure()

    // Add observer for InstanceID token refresh callback.
     NotificationCenter.default.addObserver(self,
                                           selector:  #selector(self.tokenRefreshNotification),
                                           name: .firInstanceIDTokenRefresh,
                                           object: nil)

 FIRDatabase.database().persistenceEnabled = true

    loggedInUser()
    return true
}

// [START receive_message]
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)
 }

 func application(_ application: UIApplication,  didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping  (UIBackgroundFetchResult) -> Void) {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    completionHandler(UIBackgroundFetchResult.newData)
}
// [END receive_message]
// [START refresh_token]
func tokenRefreshNotification(_ notification: Notification) {
    if let refreshedToken = FIRInstanceID.instanceID().token() {
        print("InstanceID token: \(refreshedToken)")
    }

    // Connect to FCM since connection may have failed when attempted before having a token.
    connectToFcm()
}
// [END refresh_token]
// [START connect_to_fcm]
func connectToFcm() {
    // Won't connect since there is no token
    guard FIRInstanceID.instanceID().token() != nil else {
        return;
    }

    // Disconnect previous FCM connection if it exists.
    FIRMessaging.messaging().disconnect()

    FIRMessaging.messaging().connect { (error) in
        if error != nil {
            print("Unable to connect with FCM. \(error)")
        } else {
            print("Connected to FCM.")
        }
    }
}
// [END connect_to_fcm]
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Unable to register for remote notifications: \(error.localizedDescription)")
  }

 // This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
  // If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
  // the InstanceID token.
  func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    print("APNs token retrieved: \(deviceToken)")

   // FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.unknown)

    // With swizzling disabled you must set the APNs token here.
     FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox)
}

// [START connect_on_active]
func applicationDidBecomeActive(_ application: UIApplication) {
    connectToFcm()
}
// [END connect_on_active]
// [START disconnect_from_fcm]
func applicationDidEnterBackground(_ application: UIApplication) {
    FIRMessaging.messaging().disconnect()
    print("Disconnected from FCM.")
}
// [END disconnect_from_fcm]
}

   // [START ios_10_message_handling]
 @available(iOS 10, *)
 extension AppDelegate : UNUserNotificationCenterDelegate {

// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler:   @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    // Change this to your preferred presentation option
    completionHandler([])
 }

 func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response:  UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    completionHandler()
  }
 }
  // [END ios_10_message_handling]
  // [START ios_10_data_message_handling]
 extension AppDelegate : FIRMessagingDelegate {
// Receive data message on iOS 10 devices while app is in the foreground.
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
    print(remoteMessage.appData)
}

func loggedInUser(){

    if FIRAuth.auth()!.currentUser != nil {

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let root = storyboard.instantiateViewController(withIdentifier: "menu") as! UINavigationController
        self.window?.rootViewController = root
    }




 }


}

None

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 swift 3 通过 firebase 推送通知发送图像 的相关文章

  • 在集合视图单元格中播放视频,就像在 Facebook 应用程序时间轴中播放的视频一样

    我想在集合视图单元格中播放视频 要求就像 Instagram 时间线 播放视频就像在 facebook 时间线中播放视频 为此 我使用了 UICollectionViewCell 我有一些图像 没有视频 现在我是来自画廊的图像 我正在使用相
  • 解包可选值时意外发现 nil - 使用 ALAMOFIRE

    我正在尝试使用 Alamofire 获取 JSON 格式的数据 当我使用一个 URL 时 它工作正常 当我使用另一个 URL 时 我在解包可选值时收到错误 我似乎无法追踪错误来自哪里 我已采取将代码放入 ViewDidLoad 来跟踪错误
  • 使用 Metal 高效计算 UIImage/CIImage 中有多少透明像素

    我们可以计算有多少个透明像素的最快方法是什么CIImage UIImage 例如 如果我们谈论效率 我的第一个想法是使用Metal Kernel使用任一CIColorKernel左右 但我不明白如何使用它来输出 计数 我还有其他想法 使用某
  • 从基元创建自定义形状

    我正在尝试通过组合原始形状来创建自定义物理形状 目标是创建一个圆形立方体 合适的方法似乎是初始化 形状 变换 我在这里找到的https developer apple com library prerelease ios documenta
  • 从 AVAudioRecorder 获取分贝

    我正在尝试从 AVAudio 录音机获取分贝值 这是我目前的代码 我有一个启动录音机的方法 然后是一个读取分贝值的方法 var recorder AVAudioRecorder 全局定义的记录器 然后在此处使用 func init reco
  • 在 iOS 8 中创建通话/双高状态栏?

    是否有调用自定义通话 双高状态栏的标准方法 如果没有 那么构建我自己的功能的最佳起点是哪里 我知道关于如何做到这一点存在一些多年的问题 但没有任何令人满意的答案 有什么新方法可以做到这一点吗 可能在 iOS 8 中 这里没有什么新鲜事 但我
  • 迭代嵌套的 firebase 对象 - Javascript

    如何迭代嵌套的 firebase 对象 Publications Folder1 hdgjg76675e6r Name Author hdgjdsf3275e6k hd345454575e6f Folder2
  • Flutter Firebase 身份验证 currentUser() 返回 null

    这是关于 Flutter Firebase 身份验证插件的 我试图在创建新用户后发送验证电子邮件 但 sendEmailVerification 内部使用 currentUser 这对我来说似乎是一个错误 但为了以防万一 我在 stacko
  • 如何在 Firebase Firestore 中使用多个 orderBy 查询进行排序?

    如果我想根据这种情况对文档进行排序 选择有库存的产品 通过检查名为 count 的字段 指定产品的总件数 根据另一个称为 价格 的字段对元素进行排序 看起来很简单 只需使用这段代码 DBRef collection col where co
  • Apple 针对 http 直播流媒体应用程序的政策

    这里有要求 http developer apple com library ios documentation NetworkingInternet Conceptual StreamingMediaGuide UsingHTTPLive
  • 如何快速防止标签中出现孤儿?

    我有一个可以有一两行的标签 如果它有两行 我希望第二行至少有两个 或者可能三个 单词 而不仅仅是一个 关于如何使用 swift 实现这一点有什么想法吗 提前致谢 Daniel 编辑 我删除了我愚蠢的第一个想法 这些想法并没有真正的帮助 好吧
  • 如何在 iOS 中设置视图的最大宽度?

    我的应用程序有一个基本的登录屏幕 一个外框以及其中的一些文本字段和按钮 我将框设置为填满屏幕 然而 在某些设备上这个盒子会太大 如何设置视图的最大宽度和高度 您可以使用自动布局约束 使框适应屏幕尺寸 但不超过给定的宽度和高度 为此 请对宽度
  • 在 UIView 中绘制彩色文本 -drawRect: 方法

    我正在尝试在我的中绘制彩色文本UIView子类 现在我正在使用单视图应用程序模板 用于测试 除了以下内容外 没有任何修改drawRect method 文本已绘制 但无论我将颜色设置为什么 它始终是黑色的 void drawRect CGR
  • 从 plist 文件中解码数据

    我丢失了在 Macbook Air 上用 Textwrangler 编写的文本文件中的一些数据 我在扩展名为 plist 的文件中找到了其中一些 文件是用 xml 编写的 如下所示
  • 如何在不使用 Firebase 控制台的情况下发送 Firebase 云消息通知?

    我从新的 Google 通知服务开始 Firebase Cloud Messaging 感谢这段代码https github com firebase quickstart android tree master messaging htt
  • Firebase Auth - 最近登录多长时间

    我有一个个人资料选项卡 用户可以在其中按编辑并编辑他们的个人资料 我只想在必要时才需要他们的密码 所以想知道用户登录的时间是多少毫秒 这使得它不是最近登录 其中firebase会抛出错误 auth requires recent login
  • CIAdditionCompositing 给出不正确的效果

    我正在尝试通过平均其他几个图像来创建图像 为了实现这一点 我首先将每个图像变暗 其系数等于我平均的图像数量 func darkenImage by multiplier CGFloat gt CIImage let divImage CII
  • 调用了 numberOfRowsInSection 但未调用 cellForRowAtIndexPath

    在我的表视图中节中的行数被调用两次但是cellForRowAtIndexPath不叫 我想在 tableView 中显示 Facebook 好友列表 如果 cellForRowAtIndexPath 调用我的问题就解决了 我在这里的数组中得
  • GoogleSignIn ios 附加到谷歌表格

    我目前正在开发一个 iOS 应用程序 该应用程序需要写入登录用户拥有的 Google 工作表 要登录我正在使用的用户GoogleSignInpod 并附加到我正在使用的谷歌表GoogleAPIClientForREST Sheets pod
  • ArraySlice 中的 Swift [重复]

    这个问题在这里已经有答案了 在数组上使用 prefix 方法后 我得到了所谓的 arraySlice 我怎样才能将其转换为数组 我试图从 FacebookGraphApi 获取 Ints 然后请求前 3 个 前缀 3 并尝试将它们添加到新数

随机推荐

  • ListView 行样式 - 左对齐文本和右对齐图标

    我试图让 ListView 行如下所示 Text Text Text
  • MongoDB 数据库,相当于 SELECT column1, column2 FROM tbl

    从我的 MongoDB 中我想要相当于 SELECT column1 column2 FROM tbl 通过这段代码 我得到了所有的 行 也得到了所有的 列 DBCollection collection database getColle
  • Winforms C# Outlook 风格日历

    我的任务是在 winforms C 应用程序中重新创建 MS Access 日历 我为用户创造的东西 他们讨厌 基本上 我正在将数据转储到 DataGridView 中 他们可以按月 日或员工进行搜索以获取日历事件 他们要求重新设计 使其看
  • Alamofire 具有用于快速应用程序的自定义参数编码

    我必须在我的 swift 应用程序中从 SOAP Web 服务调用一些方法 所以我认为我应该使用自定义参数编码 但是当我为此编码创建闭包时 它似乎永远不会被调用 难道我做错了什么 这是我的代码 let custom URLRequestCo
  • Spring 4,JPA,关闭控制台调试消息

    我有一个基本的 Spring 4 JPA 应用程序 我使用所有 Java 配置 根本没有 XML 我想关闭控制台调试消息 我看到了很多关于此的问题并尝试了解决方案 但我仍然看到了所有消息 控制台消息如下所示 14 58 29 301 mai
  • 从函数返回数据 (Swift)

    我正在尝试返回结果并能够从此函数访问结果数组 函数中的一切都正常工作 但是我无法返回任何内容或访问结果或从闭包外部在函数内部创建的任何变量 我想从闭包外部访问 result valueForKey id 我怎样才能做到这一点 class V
  • 错误(Xcode):意外的重复任务:目标“Runner”已将命令从“path/GoogleService-Info.plist”复制到“path/GoogleService-Info.plist”

    我尝试在正确使用 firebase 进行设置后在 iOS 上运行 flutter 项目 但收到以下与 GoogleService Info plist 相关的重复错误 这是完整的错误输出 Error output from Xcode bu
  • Angular 订阅将对象推送到数组

    我正在制作角度应用程序 并且我有一个空数组 例如 users any 然后我拨打服务电话ngOnInit将数据存储到users像数组一样 ngOnInit Getting the data from json this httpClient
  • 将 SSRS 从 2016 年降级至 2008 年

    我们有 2 个工作环境 一个用于 SSRS 2016 另一个用于 2008 我错误地在 VS2016 中打开了一份 2008 年的报告 现在我无法打开2008年的它 如何将 2016 年打开的 SSRS 报告降级回 2008 年 我设法做到
  • 在 C++ API 中将一个张量的一大块复制到另一个张量中

    我需要复制一行一个张量 在c API 转换为另一个张量的某些部分 其中开始和结束索引可用 在 C 中我们可以使用类似的东西 int myints 10 20 30 40 50 60 70 std vector
  • 自定义 Perforce RCS 关键字扩展的输出

    我想使用 RCS 关键字扩展来过滤文件 以便 Change 被翻译成1745而不是默认行为 Change 1745 我意识到这会阻止未来的扩展 但就目的而言这是可以接受的 也欢迎使用其他将更改列表编号插入文件的方法 这是我在 Perforc
  • 列表视图多重选择

    有没有办法强制列表视图控件将所有点击视为通过 Control 键完成的 我需要复制使用控制键的功能 选择项目集并取消设置其选择状态 以便允许用户轻松地同时选择多个项目 先感谢您 即使 MultiSelect 设置为 true 这也不是 Li
  • 逐字迭代字符串

    我想知道如何逐字迭代字符串 string this is a string for word in string print word 上面给出了一个输出 t h i s i s a s t r i n g 但我正在寻找以下输出 this
  • 反射值接口和指针接收器

    在golang的mongodb驱动中有以下代码 case reflect Struct if z ok v Interface Zeroer ok return z IsZero return false Zeroer 接口定义如下 typ
  • 比较 (int)double 和 (int)int 时出现异常

    嘿 我正在使用 pdCurses lib 和 stringStream 来计算并制作一个代表时钟的 5 个字符长的字符串 它显示为 00 00 0 00 00 00 或 0 000 但是 当运行我的函数时 我在这部分抛出一个异常 if in
  • 如何在Python中验证字典的结构(或模式)?

    我有一本包含配置信息的字典 my conf version 1 info conf one 2 5 conf two foo conf three False optional conf bar 我想检查字典是否遵循我需要的结构 我正在寻找
  • 有没有办法给某人打电话并在android中播放音频文件?

    我想创建一个紧急呼叫应用程序 如果触发 它会呼叫给定号码并播放音频文件 提供呼叫者无法提供的信息 为此 我需要拨打电话 但确保我可以用播放的音频文件替换扬声器中的任何声音 我可以在安卓中做到这一点吗 有什么办法呢 目前您无法使用 G1 执行
  • 自定义“AuthenticationStateProvider”身份验证失败

    我创建了一个自定义ApiAuthenticationStateProvider返回后AuthenticationState仍在说明 info Microsoft AspNetCore Authorization DefaultAuthori
  • Genymotion 中运行的虚拟设备会定期在 ADB 中离线

    我有一个在 Genymotion 2 4 中运行的 Android 设备 如果重要的话 带有 Lollipop 图像 并通过 ADB 版本 1 0 32 从本地网络中使用 Eclipse 的另一台开发人员 PC 连接到它 没有连接问题 一切
  • 如何使用 swift 3 通过 firebase 推送通知发送图像

    任何人都可以帮我发送这样的通知 我正在使用 Firebase 通知 当我发送通知时 我尝试将图像 URL 放入高级选项和键 1 的值中 图像 URL 显示在调试器中 但当我的设备中出现通知时 没有显示图像 这是我的代码 import UIK