Skip to main content

[Swift] - Custom Push Notification có hình ảnh trên iOS


1. Thiết lập Capabilities trong xcodeproj của bạn.

Truy cập xcodeproj của bạn trong xcode, chọn Capabilities và bật Push notifications và Background Modes lên > Tích chọn Remote Notifications. Xcode sẽ tạo cho bạn app id trong Apple Developer.

2. Tạo APNs để gửi thông báo.

Truy cập Apple Developer và đăng nhập, sau đó chọn: Certificates, Identifiers & Profiles > Identifiers > App IDs > Chọn app id ứng dụng của bạn và nhấp vào chỉnh sửa để cấu hình Push Notification:

Làm theo các bước và tải certificate vừa được tạo(aps_development.cer), mở certificate và thêm key.

3. Setup để gửi push cho người dùng.

Đầu tiên phải import UserNotification.
import UserNotifications
Gọi hàm didRegisterForRemoteNotificationsWithDeviceToken và didFailToRegisterForRemoteNotificationsWithError để lấy device token hoặc một số lỗi có thể xảy ra.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
  print("APNs device token: \(deviceTokenString)")
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
  print("APNs registration failed: \(error)")
}
Request sự cho phép của người dùng để gửi push, tạo một phương thức để thực hiện việc này và gọi phương thức này trong didFinishLaunchingWithOptions.
func configureNotification() {
  if #available(iOS 10.0, *) {
      let center = UNUserNotificationCenter.current()
      center.requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }
  }
  UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
  UIApplication.shared.registerForRemoteNotifications()
}
AppDelegate của bạn sẽ giống như sau:
import UIKit
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        self.configureNotification()
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
    }

    func applicationWillTerminate(_ application: UIApplication) {
    }

    func configureNotification() {
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            center.requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }
        }
        UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
        UIApplication.shared.registerForRemoteNotifications()
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
        print("APNs device token: \(deviceTokenString)")
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("APNs registration failed: \(error)")
    }
}
Việc yêu cầu ủy quyền đã xong!

5. Gửi một push bình thường để kiểm tra.

Bây giờ chạy ứng dụng của bạn với đúng certificate, có thể được trong Automatically manage signing. Sau khi chạy, hãy đặt ứng dụng của bạn ở background. Sử dụng NWPusher một công cụ để gửi push.
Sau khi cài đặt mở và chọn certificate phù hợp để gửi push cho ứng dụng của bạn, sẽ như sau:
Giờ bạn lấy device token được in ra từ console trong xcode, cần một device thật để nhận được push.

6. Bắt đầu Custom Push Notification

Sử dụng UNNotificationCategory để xác định loại notification của bạn có thể nhận được, vì điều này có thể custom push notifcation cụ thể. Trong phương thức configureNotification, chúng ta sẽ thêm UNNotificationCategory và UNNotificationAction cho push custom của chúng ta. Chỉ cần thêm mã sau vào phương thức của bạn.
func configureNotification() {
    if #available(iOS 10.0, *) {
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }
        center.delegate = notificationDelegate
        let openAction = UNNotificationAction(identifier: "OpenNotification", title: NSLocalizedString("Abrir", comment: ""), options: UNNotificationActionOptions.foreground)
        let deafultCategory = UNNotificationCategory(identifier: "CustomSamplePush", actions: [openAction], intentIdentifiers: [], options: [])
        center.setNotificationCategories(Set([deafultCategory]))
    } else {
        UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
    }
    UIApplication.shared.registerForRemoteNotifications()
}
Tiếp theo, bạn phải tạo một Notifcation Extension: vào xcodeproj trong xcode > Add Target > Notification Service Extension >Next > Finish > Activate Scheme Content.
Quay trở lại NWPusher, nhưng bây giờ push cần phải có thêm tham số mới là: “mutable-content”: ”1”.
Điều quan trọng là phải kiểm tra xem body có đúng hay không, sao chép và dán json này.
{  
   "aps":{  
      "alert":"dasdas",
      "badge":1,
      "sound":"default",
      "mutable-content":"1"
   }
}
Bây giờ để hiển thị hình ảnh trong thông báo, sử dụng UNNotificationAttachment, nhưng để thực tế hơn, chúng ta sẽ gửi hình ảnh bằng cách push và tải xuống trước khi hiển thị thông báo, vì điều này quan trọng phải sử dụng hình ảnh nhỏ, vì không thể tải xuống hình ảnh lớn.
Trong Notification Service Extension của bạn, hãy truy cập NotificationService.swift và tạo extension của UNNotificationAttachment, như sau:
@available(iOSApplicationExtension 10.0, *)
extension UNNotificationAttachment {
    
    static func saveImageToDisk(fileIdentifier: String, data: NSData, options: [NSObject : AnyObject]?) -> 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?.appendingPathComponent(fileIdentifier)
            try data.write(to: fileURL!, options: [])
            let attachment = try UNNotificationAttachment(identifier: fileIdentifier, url: fileURL!, options: options)
            return attachment
        } catch let error {
            print("error \(error)")
        }
        
        return nil
    }
}

Bây giờ chúng ta cần phải có được hình ảnh từ push, tải về và hiển thị trong push.
var urlString:String? = nil
if let urlImageString = request.content.userInfo["urlImageString"] as? String {
    urlString = urlImageString
}

if urlString != nil, let fileUrl = URL(string: urlString!) {
    print("fileUrl: \(fileUrl)")

    guard let imageData = NSData(contentsOf: fileUrl) else {
        contentHandler(bestAttemptContent)
        return
    }
    guard let attachment = UNNotificationAttachment.saveImageToDisk(fileIdentifier: "image.jpg", data: imageData, options: nil) else {
        print("error in UNNotificationAttachment.saveImageToDisk()")
        contentHandler(bestAttemptContent)
        return
    }

    bestAttemptContent.attachments = [ attachment ]
}
File NotificationService.swift hoàn chỉnh sẽ như sau:
import UserNotifications

class NotificationService: UNNotificationServiceExtension {

    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?

    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]"
            
            var urlString:String? = nil
            if let urlImageString = request.content.userInfo["urlImageString"] as? String {
                urlString = urlImageString
            }
            
            if urlString != nil, let fileUrl = URL(string: urlString!) {
                print("fileUrl: \(fileUrl)")
                
                guard let imageData = NSData(contentsOf: fileUrl) else {
                    contentHandler(bestAttemptContent)
                    return
                }
                guard let attachment = UNNotificationAttachment.saveImageToDisk(fileIdentifier: "image.jpg", data: imageData, options: nil) else {
                    print("error in UNNotificationAttachment.saveImageToDisk()")
                    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 {
            contentHandler(bestAttemptContent)
        }
    }

}

@available(iOSApplicationExtension 10.0, *)
extension UNNotificationAttachment {
    
    static func saveImageToDisk(fileIdentifier: String, data: NSData, options: [NSObject : AnyObject]?) -> 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?.appendingPathComponent(fileIdentifier)
            try data.write(to: fileURL!, options: [])
            let attachment = try UNNotificationAttachment(identifier: fileIdentifier, url: fileURL!, options: options)
            return attachment
        } catch let error {
            print("error \(error)")
        }
        
        return nil
    }
}
Sử dụng json này để push hình ảnh, tải xuống và hiển thị:
{  
   "aps":{  
      "alert":"dasdas",
      "badge":1,
      "sound":"default",
      "mutable-content":"1"
   },
   "urlImageString":"https://res.cloudinary.com/demo/image/upload/sample.jpg"
}

Quan trọng: lưu ý rằng URL hình ảnh là HTTPS nếu bạn cần hiển thị URL hình ảnh HTTP, trong plist.info của Notification Service Extension bạn phải cho phép domain hoặc cho phép mọi domain.
<key>NSAppTransportSecurity</key>
  <dict>
      <key>NSAllowsArbitraryLoads</key>
      <true/>
  </dict>
Nguồn: lucasgoesvalle.

Comments

Popular posts from this blog

RxSwift - Giới thiệu

Bạn có nghe qua về Reactive Programming chưa, đây là một khái niệm lập trình hoàn toàn mới. “Reactive Programming là lập trình theo hướng bất đồng bộ các dòng chảy dữ liệu(data streams)” Sau khi đọc khái niệm các bạn có lẽ rất mơ hồ, vậy các data streams là gì. Vậy để mình ví dụ cho các bạn: - Trong lập trình bình thường ( imperative programming ) a = b + c , tức a được gắn với kết quả cộng của b và c .Khi b với c thay đổi thì tất nhiên sẽ không ảnh hưởng tới a, nhưng trong Reactive Programming này a sẽ tự động thay đổi khi b hoặc c thay đổi, kết quả của a sẽ lập tức thay đổi theo. Vậy tại sao nên dùng RXSwift: + Giúp ứng dụng của bạn hoạt động 1 cách như là real time update ui khi có thay đổi data flow, mang đến trải nghiệm tuyệt vời cho User. + Dễ dàng lập trình bất đồng bộ (Async) thay vì phải dùng : callbacks, delegates, notifications, kvo… Bạn phải dùng nhiều thứ gây ra ứng dụng của bạn phức tạp, khó kiểm soát. + Chuyển đổi các thread khi thực hiện 1 cách...

Swift GCD part 1: Thread safe singletons

Preview Singletons are entities, referenced to the same instance of a class from everywhere in your code. It doesn't matter if you like them or not, you will definitely meet them, so it's better to understand how they work. Constructing and handling a set of data doesn't seem to be a big challenge at first glance. The problems appear when you try to optimise the user experience with background work and your app starts acting weird. ??‍♂️ After decades of watching your display mostly with a blank face, you finally realize that your data isn't handled consistently by the manager because you're accessing it (running tasks on it) from multiple threads at the same time. So you really do have to deal with making your singletons thread safe. This article series is dedicated to thread handling using Swift. In the first part below you will get a comprehensive insight into som...

Enum Initializers

In Swift Talk 45 , we wrote a small library for parsing routes. We represented routes as enums, and added a custom initializer to parse routes: enum Route { case home case users(id: Int ) } extension Route { init ?(path: String ) { if path == "/" { self = .home } else if path.hasPrefix( "/users" ) { self = .users(id: 1 ) } else { return nil } } } Of course, this code isn’t complete (see the full public episode for that). Today, we want to focus on assigning to self inside the initializer. In the initializer of any struct or enum we can treat self as a mutable variable (as if it were declared using inout ). This is why we can do the following: enum Result < A > { case success( A ) case error( Error ) } extension Result { init ( _ value: A ) { self = .success(value) } } We can even do this in a struct, although it’s easie...