Custom Push Notification with image IOS
Custom Push Notification with image IOS
I created my first custom notification, I read many articles and videos.
Is is tricky at first
So Please Focus on your work and follow These step
I follow these 3 site given link :-
1. https://medium.com/@lucasgoesvalle/custom-push-notification-with-image-and-interactions-on-ios-swift-4-ffdbde1f457
3. Link
START READY TO GO…….
1. Go to X-code and create a project
2. Go capability and select PushNotification & Back grounds Modes
3. Follow 2. Link and create certificate and install .p12 file
So we Will start to create demo
AppDelegate. swift file :-
Call didRegisterForRemoteNotificationsWithDeviceToken and didFailToRegisterForRemoteNotificationsWithError to get the device token or some failure that may happen.
import UserNotifications
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)")
}
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, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
self.configureNotification()
// Override point for customization after application launch.
return true
}
2 .Now go to your xcode proj in xcode > Add Target > Notification Service Extension >Next > Finish > Activate Scheme Content
3. Now go to your xcode proj in xcode > Add Target > Notification Content Extension >Next > Finish > Activate Scheme Content
4.Notification Service . swift file :-
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)
}
}
/ *- */
@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
}
}
5.NotificationViewController.swift
import UIKit
import UserNotifications
import UserNotificationsUI
class NotificationViewController: UIViewController, UNNotificationContentExtension {
@IBOutlet var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
}
@available(iOSApplicationExtension 10.0, *)
func didReceive(_ notification: UNNotification) {
let content = notification.request.content
if let urlImageString = content.userInfo["urlImageString"] as? String {
if let url = URL(string: urlImageString) {
URLSession.downloadImage(atURL: url) { [weak self] (data, error) in
if let _ = error {
return
}
guard let data = data else {
return
}
DispatchQueue.main.async {
self?.imageView.image = UIImage(data: data)
}
}
}
}
}
}
extension URLSession {
class func downloadImage(atURL url: URL, withCompletionHandler completionHandler: @escaping (Data?, NSError?) -> Void) {
let dataTask = URLSession.shared.dataTask(with: url) { (data, urlResponse, error) in
completionHandler(data, nil)
}
dataTask.resume()
}
}
6.NotificationViewController.swift of info file
PAYLOAD:-
You can follow Link no 3
{
"Simulator Target Bundle": "-------------write here bundleID —-------------",
"aps":{
"alert":"dasdas",
"badge":1,
"sound":"default",
"category":"CustomSamplePush",
"mutable-content":"1"
},
"urlImageString":"https://res.cloudinary.com/demo/image/upload/sample.jpg"
}
Comments
Post a Comment