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

Swift Tool Belt, Part 1: Adding a Border, Corner Radius, and Shadow to a UIView with Interface Builder

During my iOS work, I’ve assembled a set of code that I bring with me on every iOS project. I’m not talking about large frameworks or CocoaPods here. These are smaller Swift extensions or control overrides that are applicable to many projects. I think of them as my tool belt. In this post, I’ll show you an extension that will add a border, a corner radius, and a shadow to any UIView, UIButton, or UILabel and allow you to preview what it will look like in Interface Builder. Back in 2014, I wrote a blog post on Expanding User-Defined Runtime Attributes in Xcode where I added a border, corner radius, and shadow to a UIView using Interface Builder’s user-defined runtime attributes. This solution had no type checking—you had to type the property you wanted to modify by hand and often had to look up what it was called. You also had to run your project in order to see the effect of the runtime attribute. Starting with Xcode 6 , there is a new mech...

Alamofire vs URLSession

Alamofire vs URLSession: a comparison for networking in Swift Alamofire and URLSession both help you to make network requests in Swift. The URLSession API is part of the foundation framework, whereas Alamofire needs to be added as an external dependency. Many  developers  doubt  whether it’s needed to include an extra dependency on something basic like networking in Swift. In the end, it’s perfectly doable to implement a networking layer with the great URLSession API’s which are available nowadays. This blog post is here to compare both frameworks and to find out when to add Alamofire as an external dependency. Build better iOS apps faster Looking for a great mobile CI/CD solution that has tons of iOS-specific tools, smooth code signing, and even real device testing? Learn more about Bitrise’s iOS specific solutions! This shows the real power of Alamofire as the framework makes a lot of things easier. What is Alamofire? Where URLSession...

Frame vs Bounds in iOS

This article is a repost of an answer I wrote on Stack Overflow . Short description frame = a view’s location and size using the parent view’s coordinate system ( important for placing the view in the parent) bounds = a view’s location and size using its own coordinate system (important for placing the view’s content or subviews within itself) Details To help me remember frame , I think of a picture frame on a wall . The picture frame is like the border of a view. I can hang the picture anywhere I want on the wall. In the same way, I can put a view anywhere I want inside a parent view (also called a superview). The parent view is like the wall. The origin of the coordinate system in iOS is the top left. We can put our view at the origin of the superview by setting the view frame’s x-y coordinates to (0, 0), which is like hanging our picture in the very top left corner of the wall. To move it right, increase x, to move it down increase y. To help me remember bound...