iosswiftios-extensionsunnotificationattachmentunnotificationserviceextension

What is the file size limit in temporary directory in iOS?


I am trying to save an image of size 7.9MB downloaded from here. But at line 'try data.write...' the extension crashes and I get this in console.

kernel EXC_RESOURCE -> Notification Extension[3137] exceeded mem limit: ActiveHard 12 MB (fatal)

kernel 46710.034 memorystatus: killing_specific_process pid 3137 [Notification Extension] (per-process-limit 3) - memorystatus_available_pages: 73906

ReportCrash starting prolongation transaction timer default 18:39:53.104640 +0530

ReportCrash Process Notification Extension [3137] killed by jetsam reason per-process-limit

Is it because 7.9MB size is too much for it too handle. If it is then it doesn't make sense as it is necessary to save media in temporary storage before creating an UNNotificationAttachment object. In official documentation the limit for png files is given as 10 MB and for videos it is 50 MB. How do I solve this?

let fileManager = FileManager.default
let folderName = ProcessInfo.processInfo.globallyUniqueString

guard let folderURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(folderName, isDirectory: true) else {
        return nil
}

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 {

}

Solution

  • It worked this way. Instead of downloading data using NSData(contentsOf:), I used URLSession.shared.downloadTask(with:). This stores the downloaded data by itself so no need for us to write it. It just has to be moved to desired temporary location using FileManager.shared.moveItem(at:to:). Looks like the problem was with NSData.write(to:options:)function. It has some size limit on it.

    URLSession.shared.downloadTask(with: url) { (location, response, error) in
    
        if let location = location {
            let tmpDirectory = NSTemporaryDirectory()
            let tmpFile = "file://".appending(tmpDirectory).appending(url.lastPathComponent)
            let tmpUrl = URL(string: tmpFile)!
            try! FileManager.default.moveItem(at: location, to: tmpUrl)
            if let attachment = try? UNNotificationAttachment(identifier: "notification-img", url: tmpUrl) {
            bestAttemptContent.attachments = [attachment]
            }
        }
        contentHandler(bestAttemptContent)
    }.resume()