Skip to content

Instantly share code, notes, and snippets.

@acalism
Created March 6, 2018 07:39
Show Gist options
  • Save acalism/237029aa721b0783d99ca4f1ec9d7727 to your computer and use it in GitHub Desktop.
Save acalism/237029aa721b0783d99ca4f1ec9d7727 to your computer and use it in GitHub Desktop.
App Extension: Notifiation Content
import UIKit
import UserNotifications
import UserNotificationsUI
// 可考虑在 info.plist 里限定初始高与屏幕高的比例,比如 0.3,但不建议使用1。体验一下加载图片的效果就知道为什么了
class NotificationViewController: UIViewController, UNNotificationContentExtension {
//@IBOutlet var label: UILabel?
@IBOutlet var imageView: UIImageView! // 建议在storyboard限定图片最大高度和最大宽度,避免图片被截断
//@IBOutlet var containerView: UIView!
// 最终显示尺寸的秘密:
// 1. 对imageView的约束,会给出最终显示尺寸的信息;
// 2. 或在 viewDidLoad() 指定 preferredContentSize
override func viewDidLoad() {
super.viewDidLoad()
// Do any required interface initialization here.
view.backgroundColor = .white // Xcode自动创建的默认为蓝色
}
func didReceive(_ notification: UNNotification) {
let c = notification.request.content
//label?.text = c.body
// if UTTypeConformsTo(kUTTypeJPEG as CFString, kUTTypeImage as CFString) {
// print(true)
// }
for a in c.attachments {
print(a)
if a.url.startAccessingSecurityScopedResource() {
let data = try! Data.init(contentsOf: a.url)
// 若不用 async,就显示不出来。
// Debug 时此处打断点,能显示图片
DispatchQueue.main.async {
let i = UIImage(data: data)
self.imageView.image = i
//imageView.setNeedsDisplay()
}
a.url.stopAccessingSecurityScopedResource()
}
}
}
func didReceive(_ response: UNNotificationResponse, completionHandler completion: @escaping (UNNotificationContentExtensionResponseOption) -> Void) {
print(response)
completion(.dismissAndForwardAction)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment