วิธีติดตั้ง Notification Serviceให้กับ Application บน iOS

YANYONG PUMKUMARN
te<h @TDG
Published in
3 min readOct 25, 2021

Notification เป็น Feature ที่ส่วนเสริมที่ เป็นช่องทาง แจ้งข่าวสารจากผู้พัฒนา ถึงคนใช้งานแอปฟลิเคชั่น ยกตัวอย่างการใช้งาน notification

1 แอปฟลิเคชั่น แชท จำเป็นจะต้องส่งแจ้งเตือนเพื่อให้ ปลายทางรับรู้ข้อความ

2 แอปฟลิเคชั่น อีคอมเมริช จะใช้การแจ้งเตือน โปรโมชั่นต่างๆ ให้ผู้ใช้รับทราบข่าวสารล่วงหน้าและ ยังพัฒนาให้สามารถนำพาไปยังหน้าต่างๆภายในแอปฟลิเคชั่นได้อีกด้วย

ในบทความนี้จะอธิบายเกี่ยวกับ การติดตั้งภายในโปรเจกต์ สำหรับ แอปฟลิเคชั่นที่ต้องการจะใช้งาน Notifications

เริ่มต้นเราจะเปิดโปรเจกต์ และ เลือกที่ General

ด้านล่าง กด ”+” เพื่อเพิ่ม Extension

ค้นหา Notification และเลือกที่เป็น Notification Service Extension

จากนั้นเราต้องกด Activate เพื่อสร้าง entitlement ขึ้นมาสำหรับ Target ครับ

จะได้ Target ขึ้นมาแบบนี้ครับ

จากนั้นเพิ่ม Push Notification ที่ signing & Capabilities ครับ

จากนั้นเราจะมาเขียน code เพื่อใช้งานกันครับ

ก่อน อื่นเลือก file ที่เราอยากจะเป็น ทางเข้าออกสำหรับ notification โดยปกติแล้วจะเลือกใช้เป็น Appdelegate หรือในช่วงหลังที่เปลี่ยนมาใช้เป็น SceneDelegate ก็ได้เช่นกันครับ

import UserNotificationsfunc registerForPushNotifications() {

UNUserNotificationCenter.current() .requestAuthorization(options: [.alert, .sound, .badge]) { granted, _ in


}
}

จุดนี้จะเป็นการ ขอ permission สำหรับ Notification

เมื่อ code ข้างบนทำงานจะได้ popup แบบนี้ครับ

เราจะทำการ setup delegate ไว้บน scenedelegate นะครับ
SceneDelegate: UNUserNotificationCenterDelegate

และ เพิ่ม call back token ที่ AppDelegate เพื่อเก็บ token ไว้ส่งให้หลังบ้านไปใช้งานต่อ

func application(
_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
) {
let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
let token = tokenParts.joined()
debugPrint("Device Token: \(token)")
}
func application(
_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error
) {
print("Failed to register: \(error)")
}

ส่วนนี้จะเป็น mock json เพื่อเอาไปทดสอบ ด้วย App Push Notification ที่มีให้ทดสอบฟรีบน App Store นะครับ ผมยกตัวอย่างเป็น Push Hero ครับ
https://apps.apple.com/app/id1499227284
ใช้ token ที่เก็บมาจากด้านบน มาใส่ภายใน Push Hero แล้วยิงได้เลยครับ

{
"aps": {
"alert": "Notification!",
"sound": "default",
"bagde": 1
}
}

ข้างต้น เรา setup ใน application เรียบร้อย แล้วครับ

เราก็จะสามารถยิง notification เข้ามาที่ application ได้เรียบร้อยแล้ว

ตัวอย่างหน้าตา Push Hero จะใช้ป Bundle Id และ token ที่นำมาแล้วสามารถยิงได้เลยครับ

อีกอย่างที่เราต้องใช้ คือ p12 ที่ได้จากการ Setup Push Notification บน Developer Console ของ apple ครับ
เมื่อเรา config สำเร็จจะสามารถกด send ได้หลังจากนั้นจะมี
หลังจากที่ยิงสำเร็จจะขึ้น Responsse ประมาณนี้ครับ

--

--