🐛 Bug fixes on iOS native image

This commit is contained in:
2024-12-21 16:10:53 +08:00
parent d6d60e60a9
commit f5c06bc89c
7 changed files with 67 additions and 65 deletions

View File

@ -7,6 +7,7 @@
import UserNotifications
import Intents
import Kingfisher
enum ParseNotificationPayloadError: Error {
case missingMetadata(String)
@ -18,58 +19,6 @@ class NotificationService: UNNotificationServiceExtension {
private var contentHandler: ((UNNotificationContent) -> Void)?
private var bestAttemptContent: UNMutableNotificationContent?
private func fetchAvatarImage(from url: String, completion: @escaping (INImage?) -> Void) {
guard let imageURL = URL(string: url) else {
completion(nil)
return
}
// Define a cache location based on the URL hash
let cacheFileName = imageURL.lastPathComponent
let tempDirectory = FileManager.default.temporaryDirectory
let cachedFileUrl = tempDirectory.appendingPathComponent(cacheFileName)
// Check if the image is already cached
if FileManager.default.fileExists(atPath: cachedFileUrl.path) {
do {
let data = try Data(contentsOf: cachedFileUrl)
let cachedImage = INImage(imageData: data) // No optional binding here
completion(cachedImage)
return
} catch {
print("Failed to load cached avatar image: \(error.localizedDescription)")
try? FileManager.default.removeItem(at: cachedFileUrl) // Clear corrupted cache
}
}
// Download the image if not cached
let session = URLSession(configuration: .default)
session.downloadTask(with: imageURL) { localUrl, response, error in
if let error = error {
print("Failed to fetch avatar image: \(error.localizedDescription)")
completion(nil)
return
}
guard let localUrl = localUrl, let data = try? Data(contentsOf: localUrl) else {
print("Failed to fetch data for avatar image.")
completion(nil)
return
}
do {
// Cache the downloaded file
try FileManager.default.moveItem(at: localUrl, to: cachedFileUrl)
} catch {
print("Failed to cache avatar image: \(error.localizedDescription)")
}
// Create INImage from the downloaded data
let inImage = INImage(imageData: data) // Create directly
completion(inImage)
}.resume()
}
override func didReceive(
_ request: UNNotificationRequest,
withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void
@ -112,16 +61,23 @@ class NotificationService: UNNotificationServiceExtension {
throw ParseNotificationPayloadError.missingAvatarUrl("The notification has no avatar.")
}
let metadataCopy = metadata as? [String: String] ?? [:]
let avatarUrl = getAttachmentUrl(for: avatarIdentifier)
fetchAvatarImage(from: avatarUrl) { [weak self] inImage in
guard let self = self else { return }
let handle = INPersonHandle(value: "\(metadata["user_id"] ?? "")", type: .unknown)
KingfisherManager.shared.retrieveImage(with: URL(string: avatarUrl)!, completionHandler: { result in
var image: Data?
switch result {
case .success(let value):
image = value.image.pngData()
case .failure(let error):
print("Unable to get avatar url: \(error)")
}
let handle = INPersonHandle(value: "\(metadataCopy["user_id"] ?? "")", type: .unknown)
let sender = INPerson(
personHandle: handle,
nameComponents: nil,
displayName: content.title,
image: inImage,
image: image == nil ? nil : INImage(imageData: image!),
contactIdentifier: nil,
customIdentifier: nil
)
@ -132,12 +88,12 @@ class NotificationService: UNNotificationServiceExtension {
let updatedContent = try? request.content.updating(from: intent)
self.contentHandler?(updatedContent ?? content)
} else {
let intent = self.createMessageIntent(with: sender, metadata: metadata, body: content.body)
let intent = self.createMessageIntent(with: sender, metadata: metadataCopy, body: content.body)
self.donateInteraction(for: intent)
let updatedContent = try? request.content.updating(from: intent)
self.contentHandler?(updatedContent ?? content)
}
}
})
}
private func handleDefaultNotification(content: UNMutableNotificationContent) throws {