Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Notification #5

Open
wants to merge 8 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
-
  • Loading branch information
janak-jivrani committed Mar 28, 2024
commit a7d88e2ebfd7a0f413ff992c1e5e55e149c7091e
47 changes: 41 additions & 6 deletions MageNotification/NotificationService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,56 @@ class NotificationService: UNNotificationServiceExtension {
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)

if let bestAttemptContent = bestAttemptContent {
// Modify the notification content here...
bestAttemptContent.title = "\(bestAttemptContent.title) [modified]"


if let bestAttemptContent = bestAttemptContent,
// ✅ payload
let fcmOptionsUserInfo = bestAttemptContent.userInfo["attachment"] as? [String: Any] {
guard let imageURLString = fcmOptionsUserInfo["image"] as? String else {
contentHandler(bestAttemptContent)
return
}
let imageURL = URL(string: imageURLString)!

// 🔥 download image.
guard let imageData = try? Data(contentsOf: imageURL) else {
contentHandler(bestAttemptContent)
return
}

// 🔥 set UNNotificationAttachment.
guard let attachment = UNNotificationAttachment.saveImageToDisk(identifier: "notification.jpg", data: imageData, options: nil) else {
contentHandler(bestAttemptContent)
return
}
bestAttemptContent.attachments = [attachment]
contentHandler(bestAttemptContent)
}
}

override func serviceExtensionTimeWillExpire() {
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
}

extension UNNotificationAttachment {
static func saveImageToDisk(identifier: String, data: Data, options: [AnyHashable : Any]? = nil) -> UNNotificationAttachment? {
let fileManager = FileManager.default
let folderName = ProcessInfo.processInfo.globallyUniqueString
let folderURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(folderName, isDirectory: true)!

do {
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true, attributes: nil)
let fileURL = folderURL.appendingPathExtension(identifier)
try data.write(to: fileURL)
let attachment = try UNNotificationAttachment(identifier: identifier, url: fileURL, options: options)
return attachment
} catch {
print("saveImageToDisk error - \(error)")
}
return nil
}
}
46 changes: 46 additions & 0 deletions Shared/Extensions/NotificationManager/NotificationManager.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@


import FirebaseCore
import FirebaseMessaging
import UserNotifications

protocol NotificationManagerDelegate {
func didReceiveNotificationToken(token: String)
}

class NotificationManager: NSObject, MessagingDelegate, UNUserNotificationCenterDelegate {

var delegate: NotificationManagerDelegate?

func registerForPushNotifications() {
Messaging.messaging().delegate = self
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
}
UIApplication.shared.registerForRemoteNotifications()
updateFirestorePushTokenIfNeeded()
}

func updateFirestorePushTokenIfNeeded() {
if let token = Messaging.messaging().fcmToken {
delegate?.didReceiveNotificationToken(token: token)
}
}

func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
updateFirestorePushTokenIfNeeded()
}

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("response, ", response)
}

}
20 changes: 19 additions & 1 deletion Shared/MageApp/MageApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,34 @@

import SwiftUI
import FirebaseCore
import FirebaseMessaging

class AppDelegate: UIResponder, UIApplicationDelegate {

func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()

let notificationManager = NotificationManager()
notificationManager.delegate = self
notificationManager.registerForPushNotifications()

return true
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
// Messaging.messaging().setAPNSToken(deviceToken, type: .unknown)
}

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {

return true
}
}

extension AppDelegate: NotificationManagerDelegate {

func didReceiveNotificationToken(token: String) {
print("FCM Token: ", token)
}
}
6 changes: 2 additions & 4 deletions Shared/Screens/BrowseScreen.swift
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,7 @@ struct BrowseScreen: View {

struct BrowseScreen_Previews: PreviewProvider {
static var previews: some View {
NavigationStack {
BrowseScreen()
.environmentObject(ChannelModel())
}
BrowseScreen()
.environmentObject(ChannelModel())
}
}
6 changes: 2 additions & 4 deletions Shared/Screens/ChannelScreen.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@ struct ChannelScreen: View {

struct ChannelScreen_Previews: PreviewProvider {
static var previews: some View {
NavigationStack {
ChannelScreen(channel: Channel(_id: "01234", title: "Test Channel", description: "Test channel description", userDetails: User(_id: "1234", username: "testgagansuie", displayName: "Test Gagan Suie", avatar: "img" )))
.environmentObject(ChannelModel())
}
ChannelScreen(channel: Channel(_id: "01234", title: "Test Channel", description: "Test channel description", userDetails: User(_id: "1234", username: "testgagansuie", displayName: "Test Gagan Suie", avatar: "img" )))
.environmentObject(ChannelModel())
}
}
3 changes: 2 additions & 1 deletion Shared/mage_iosApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ import SwiftUI
struct mage_iosApp: App {

@State var isFromLogin = false

@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

var body: some Scene {
WindowGroup {
LogInScreen(isLogin: _isFromLogin)
Expand Down
2 changes: 2 additions & 0 deletions mage-ios--iOS--Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
</array>
</dict>
</array>
<key>FirebaseAppDelegateProxyEnabled</key>
<false/>
<key>UIAppFonts</key>
<array>
<string>Poppins-Black.ttf</string>
Expand Down
Loading