iosswift3rich-notifications

iOS 10 remote notifications with pictures


First of all I'm new developing with Swift, I have an Objective C background, but I'm mainly an Android developer.

Actually I'm developing an app in Swift 3 and Xcode 8. I need to add to this application the new rich push notification system of Apple.

I have been able to add a local rich notification example with pics, videos and gifs. But I need to show remote notifications with pics hosted on a typical Internet server.

To launch local notifications I'm using this code:

@IBAction func launchPicNotification(sender: UIButton) {
    let content = UNMutableNotificationContent()
    content.title = "Title"
    content.body = "Body"
    content.sound = UNNotificationSound.default()

    let url = Bundle.main.url(forResource:"foto", withExtension: "jpg")

    let attachment = try? UNNotificationAttachment(identifier: "Notification",
                                                   url: url!,
                                                   options: [:])

    if let attachment = attachment {
        print("Yes")
        content.attachments.append(attachment)
    }else{
        print("No")
    }

    let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 10.0, repeats: false)
    let request = UNNotificationRequest(identifier:"identificador", content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request){(error) in

        if (error != nil){

            //handle here

        }

    }
}

I need to load a remote jpg file as attached image. Does somebody know how can I load a remote file instead of load a local picture?

Thanks


Solution

  • I added an extension to UIImage to handle this. Once you create a UIImage from the downloaded data, you can call this function to create a local URL.

    extension UIImage {
    
    func createLocalURL() -> URL? {
    
        guard let data = UIImagePNGRepresentation(self) else {
            print("Coule not get UIImagePNGRepresentation Data for photo")
            return nil
        }
    
        let localUrl = self.getDocumentsDirectory().appendingPathComponent("copy.png")
    
        do {
            try data.write(to: localUrl)
        } catch let error {
            print("Failed to write to URL")
            print(error)
        }
        return localUrl
    }
    
    }