作者:宇剑小窝_911 | 来源:互联网 | 2023-02-01 14:44
我正在开发一个使用照片共享扩展程序的iOS应用程序,其中处理图像并触发我们的主要功能.
在Photo的应用程序的模拟器中,这很好用.我决定使用Photo的应用程序在设备上运行它也很棒,但是当我截图并尝试从iOS 11的新"快速截图"分享时,扩展程序崩溃,任何想法?
扩展程序获取图像,将其发送到服务器,获取响应并显示该响应(所有内容都在扩展中).当我从快速截图访问时,Messenger和Snapchat共享扩展仍然有用,这让我很烦恼!
Xcode 9也没有给我任何来自共享扩展的日志.同样值得注意的是,每次我在设备上重新安装应用程序时,我都在使用我需要"信任"的开发者帐户.
码:
// App Group keys
let suiteName = "group.suite.id"
override func viewDidLoad() {
print("Styling views..")
styleViews()
print("Styled views")
print("Adding notifications..")
addNotifications()
print("Added notifications")
print("Fetching image..")
fetchSharedImage()
}
func styleViews(){
// Set up main view
mainView.layer.cornerRadius = 8
mainShadowView.addShadow()
// Set up views and buttons
// Code hidden, applies shadows etc.
// Code hidden, moves constraints of a view
}
func addNotifications(){
// Helps views tell their parent (this view controller) to navigate to another form
NotificationCenter.default.addObserver(forName: NotificationDisplayFetchedLink, object: nil, queue: nil){ notification in
// Handles user info in lambda block
guard let userInfo = notification.userInfo,
let link = userInfo["link"] as? String
else {
print("No userInfo found in notification")
return
}
self.displayResult(with: link)
}
}
func fetchSharedImage(){
// Make sure we have a valid extension item
if let cOntent= extensionContext!.inputItems[0] as? NSExtensionItem {
let cOntentType= kUTTypeImage as String
// Verify the provider is valid
if let cOntents= content.attachments as? [NSItemProvider] {
// look for images
for attachment in contents {
if attachment.hasItemConformingToTypeIdentifier(contentType) {
attachment.loadItem(forTypeIdentifier: contentType, options: nil) { data, error in
let url = data as! URL
if let imageData = try? Data(contentsOf: url) {
self.selectedImage = UIImage(data: imageData)
DispatchQueue.main.async {
self.selectedImageView.layer.cornerRadius = 8
self.selectedImageView.image = self.selectedImage
}
self.makeWebRequest()
}
}
}
}
}
}
}
func makeWebRequest(){
let url = URL(string: "url.json")
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
// Data is empty
return
}
let json = try! JSONSerialization.jsonObject(with: data, options: []) as! NSDictionary
guard let dict = json as? [String:Any] else { return }
let item = dict["item"]
guard let itemData = item as? [[String:Any]] else { return }
let link = itemData[0]["url"]
NotificationCenter.default.post(name: NotificationDisplayFetchedLink, object: nil, userInfo: [link: link!])
}
task.resume()
}
编辑:
所以解决方案(正如Owen Zhao所说)是iOS 11截图编辑器返回UIImage,而像Photos这样的应用程序会返回URL.
我优雅地处理这个问题的解决方案是将UIImage或URL转换为UIImage到iOS临时目录(3天后删除),然后将该目录中图像的URL保存到共享扩展.
1> Owen Zhao..:
let url = data as! URL
if let imageData = try? Data(contentsOf: url) {
问题是因为这里的数据不是URL.它是一个"public.image",尝试转换为UIImage而不是Data.