【发布时间】:2017-08-26 16:35:08
【问题描述】:
您好,我已经为我的应用程序实现了共享扩展程序,它从图库中选择图像并发送到特定视图。现在的问题是当我试图保存图像数组(从画廊中挑选的图像)
func manageImages() {
let content = extensionContext!.inputItems[0] as! NSExtensionItem
let contentType = kUTTypeImage as String
for (index, attachment) in (content.attachments as! [NSItemProvider]).enumerated() {
if attachment.hasItemConformingToTypeIdentifier(contentType) {
attachment.loadItem(forTypeIdentifier: contentType, options: nil) { data, error in
if error == nil, let url = data as? URL {
do {
let imageData = try Data(contentsOf: url)
let image = UIImage(data: imageData)
self.selectedImages.append(image!)
if index == (content.attachments?.count)! - 1 {
self.imgCollectionView.reloadData()
UserDefaults.standard.set(self.selectedImages, forKey: "PHOTOKEY")
UserDefaults.standard.synchronize()
}
}
catch let exp {
print("GETTING ERROR \(exp.localizedDescription)")
}
} else {
print("GETTING ERROR")
let alert = UIAlertController(title: "Error", message: "Error loading image", preferredStyle: .alert)
let action = UIAlertAction(title: "Error", style: .cancel) { _ in
self.dismiss(animated: true, completion: nil)
}
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
}
}
}
}
并在 AppDelegate 方法中获取该数组
func application(_ app: UIApplication,
open url: URL,
options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
if let key = url.absoluteString.components(separatedBy: "=").last, let _ = UserDefaults.standard.array(forKey: key) {
let myVC = UIStoryboard.getViewController(storyboardName: "Main",
storyboardId: "MyViewController")
let navVC = UIStoryboard.getViewController(storyboardName: "Main",
storyboardId: "MyNavigationVC") as! UINavigationController
navVC.viewControllers.append(myVC)
self.window?.rootViewController = navVC
self.window?.makeKeyAndVisible()
return true
}
return false
}
我正在发送 url let url = URL(string: "unfoldsPrintsShare://dataUrl=PHOTOKEY") 并且能够获得 PHOTOKEY
成功但数组为零,因此条件为假。
我该怎么办?,我google了很多,但没有找到任何答案
当我尝试通过调试附加扩展进程时,我也没有收到日志。
附: : 使用 Xcode 8.3.3 iOS 10.3, iPhone 6 物理设备
更新:也尝试通过应用组套装名称
let userDefaults = UserDefaults(suiteName: "group.com.company.appName")
userDefaults?.set(self.selectedImages, forKey: "PHOTOKEY")
userDefaults?.synchronize()
还是没有运气
【问题讨论】:
-
我认为您无法在 userdefaults 中存储 UIImage 数组。您必须将它们转换为具有 UIImagePNGRepresentation 之类的数组 NSData 并在启动应用程序时再次返回。
-
Userdefaults 也可能不是共享图像的最佳方式。我还没有研究过,但是与您的应用程序组共享目录之类的东西可能会更好:developer.apple.com/documentation/foundation/nsfilemanager/…
-
我也尝试保存在文档目录中,但它也给出了 nil
-
你能给出一个我可以尝试的答案吗@StefanChurch
标签: ios swift nsuserdefaults ios8-share-extension