我有一个用Swift编写的共享扩展名,我想用它将.zip文件保存到应用程序组中,以便以后通过我的应用程序访问它。我可以使用它,但是它不能始终保存文件。有时它可以完美运行,但大多数情况下它仅触发didSelectPost()
功能,但没有将文件保存到App组中。
这是我用于将存档保存到应用程序组的代码
import UIKit
import Social
import MobileCoreServices
class ShareViewController: SLComposeServiceViewController {
let suiteName = "group.sharesheetTest"
override func isContentValid() -> Bool {
// Do validation of contentText and/or NSExtensionContext attachments here
return true
}
override func didSelectPost() {
let type = kUTTypeArchive as String
// This is called after the user selects Post. Do the upload of contentText and/or NSExtensionContext attachments.
if let content = extensionContext!.inputItems[0] as? NSExtensionItem {
if let contents = content.attachments {
for attachment in contents {
attachment.loadItem(forTypeIdentifier:type , options: nil){ data, error in
let url = data as! URL
if let fileData= try? Data(contentsOf: url) {
let fileName = url.lastPathComponent
self.saveFileToGroup(zipName:fileName, data:fileData )
}
}
}
}
}
// Inform the host that we're done, so it un-blocks its UI. Note: Alternatively you could call super's -didSelectPost, which will similarly complete the extension context.
self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
}
override func configurationItems() -> [Any]! {
// To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here.
return []
}
// Saves a zip to group
func saveFileToGroup(zipName: String ,data: Data) {
let sharedContainerURL :URL? = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.sharesheetTest")
let dataPath = sharedContainerURL!.appendingPathComponent("zipFiles")
//check if folder exists
do {
try FileManager.default.createDirectory(atPath: dataPath.path, withIntermediateDirectories: true, attributes: nil)
} catch {
print(error)
}
//add file name to URL
let fileName = dataPath.appendingPathComponent(zipName)
print(fileName)
//write file to shared container
do {
try data.write(to: fileName)
} catch {
print(error)
}
print("saved")
}
}
[如果有人能弄清楚为什么它不能始终如一地工作,我将不胜感激
我也一样,找不到根本原因。