Skip to content

Commit

Permalink
[Feat/#71] add delegate setting for noti in DDooingApp file
Browse files Browse the repository at this point in the history
  • Loading branch information
jihee-daily committed May 24, 2024
1 parent 5bb348e commit 7d50f36
Show file tree
Hide file tree
Showing 3 changed files with 137 additions and 8 deletions.
8 changes: 8 additions & 0 deletions DDooing/DDooing.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
10DDE25C2C00F7F40084E1BF /* NotificationDataModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10DDE25A2C00F7F40084E1BF /* NotificationDataModel.swift */; };
10DDE25D2C00F7F40084E1BF /* NotificationDataModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10DDE25A2C00F7F40084E1BF /* NotificationDataModel.swift */; };
10DDE25E2C00F7F40084E1BF /* NotificationDataModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10DDE25A2C00F7F40084E1BF /* NotificationDataModel.swift */; };
10DDE2602C00F9AA0084E1BF /* FirebaseMessaging in Frameworks */ = {isa = PBXBuildFile; productRef = 10DDE25F2C00F9AA0084E1BF /* FirebaseMessaging */; };
4F1A593D2BF8892000C3EF2C /* Pretendard-ExtraBold.otf in Resources */ = {isa = PBXBuildFile; fileRef = 4F1A59342BF8892000C3EF2C /* Pretendard-ExtraBold.otf */; };
4F1A593E2BF8892000C3EF2C /* Pretendard-ExtraBold.otf in Resources */ = {isa = PBXBuildFile; fileRef = 4F1A59342BF8892000C3EF2C /* Pretendard-ExtraBold.otf */; };
4F1A593F2BF8892000C3EF2C /* Pretendard-ExtraBold.otf in Resources */ = {isa = PBXBuildFile; fileRef = 4F1A59342BF8892000C3EF2C /* Pretendard-ExtraBold.otf */; };
Expand Down Expand Up @@ -189,6 +190,7 @@
files = (
4FD812D32BF87AB900F16ED0 /* FirebaseDatabaseSwift in Frameworks */,
4FD812D12BF87AB900F16ED0 /* FirebaseDatabase in Frameworks */,
10DDE2602C00F9AA0084E1BF /* FirebaseMessaging in Frameworks */,
4FD812CD2BF87AB900F16ED0 /* FirebaseAnalytics in Frameworks */,
4FD812D52BF87AB900F16ED0 /* FirebaseFirestore in Frameworks */,
4FD812CF2BF87AB900F16ED0 /* FirebaseAuth in Frameworks */,
Expand Down Expand Up @@ -451,6 +453,7 @@
4FD812D22BF87AB900F16ED0 /* FirebaseDatabaseSwift */,
4FD812D42BF87AB900F16ED0 /* FirebaseFirestore */,
4FD812D62BF87AB900F16ED0 /* FirebaseFirestoreSwift */,
10DDE25F2C00F9AA0084E1BF /* FirebaseMessaging */,
);
productName = DDooing;
productReference = 4FAD25AC2BF3339A00EBD37A /* DDooing.app */;
Expand Down Expand Up @@ -1102,6 +1105,11 @@
/* End XCRemoteSwiftPackageReference section */

/* Begin XCSwiftPackageProductDependency section */
10DDE25F2C00F9AA0084E1BF /* FirebaseMessaging */ = {
isa = XCSwiftPackageProductDependency;
package = 4FD812C72BF8798A00F16ED0 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */;
productName = FirebaseMessaging;
};
4FBE64D12BFDD572008363A0 /* FirebaseAnalytics */ = {
isa = XCSwiftPackageProductDependency;
package = 4FD812C72BF8798A00F16ED0 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */;
Expand Down
128 changes: 128 additions & 0 deletions DDooing/DDooing/Views/DDooingApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,137 @@ struct DDooingApp: App {
}
}

// Initializing firebase and cloud messaging
class AppDelegate: NSObject, UIApplicationDelegate {
let gcmMessageIDKey = "gcm.message_id"

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

FirebaseApp.configure()

// Setting cloud messaging
Messaging.messaging().delegate = self

// Setting notifications
UNUserNotificationCenter.current().delegate = self

let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: { _, _ in }
)

application.registerForRemoteNotifications()

return true
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

// Do something with message data here.

UIImpactFeedbackGenerator(style: .medium).impactOccurred()

if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}

// Print full message.
print(userInfo)

completionHandler(UIBackgroundFetchResult.newData)
}

// In order to receive notifications you need implement these methods.
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: any Error) {

}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Messaging.messaging().token { token, error in
// if let error = error {
// print("Error fetching FCM registration token: \(error)")
// } else if let token = token {
// print("FCM registration token: \(token)")
//// self.fcmRegTokenMessage.text = "Remote FCM registration token: \(token)"
// }
// }
}


}

// Cloud messaging
extension AppDelegate: MessagingDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
print("Firebase register action token:")

// Store this token to firebase and retrieve when to send message to someone.
let dataDict: [String: String] = ["token": fcmToken ?? ""]

if let user = Auth.auth().currentUser {
setUsersFCMToken(token: fcmToken!, userAUID: user.uid)
}

// Store token in firestore for sending notifications from server in future
print(dataDict)
}

private func setUsersFCMToken(token : String, userAUID: String) {
let db = Firestore.firestore()

db.collection("Users").document(userAUID).updateData([
"deviceToken": token
]) { err in
if let err = err {
print("Error updating document: \(err)")
} else {
print("토큰 저장 성공 : \(token)")
}
}
}
}

// User notifications (InApp Notifications)
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo

// Haptics
// UIImpactFeedbackGenerator(style: .medium).impactOccurred()

// Do something with message data.
print("User Info: \(userInfo)")
if let aps = userInfo["aps"] as? [String: Any],
let alert = aps["alert"] as? [String: String],
let body = alert["body"],
let title = alert["title"] {
// body와 title 값을 추출했습니다.
// 여기서 SwiftData를 사용하여 값을 저장합니다.
// saveNotificationData(body: body, title: title)
print("User alert: \(alert)")
print("User body: \(body)")
print("User title: \(title)")
}

completionHandler([[.banner, .badge, .sound]])
}


func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo

if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}

print("User Info: \(userInfo)")

completionHandler()
}
}
9 changes: 1 addition & 8 deletions DDooing/DDooing/Views/Home/HomeView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -89,14 +89,7 @@ struct HomeView: View {
Text("\(postPositionText(name)) 생각하며 눌러보세요.")
.font(.headline)
.padding(.bottom,60)








Spacer()
}
.padding()
.onAppear {
Expand Down

0 comments on commit 7d50f36

Please sign in to comment.