我有一个应用程序和一个共享扩展程序。该扩展程序在this之类的arXiv页面上运行。然后提取一些信息,包括PDF网址,并应告知主应用程序保存数据。
这是现在发生的事情:
根据我的read,我无法共享一个领域数据库,而必须同步两个领域。同样,将文件写在共享容器上似乎也是不必要的。因此,我希望共享应用程序告诉主应用程序运行一个命令,该命令将完成主应用程序中的第2步和第3步。
这是我为3个步骤编写的代码:
override func didSelectPost() {
var parameters: [String: String] = [:]
let extensionItem = extensionContext?.inputItems.first as! NSExtensionItem
let itemProvider = extensionItem.attachments?.first as! NSItemProvider
let propertyList = String(kUTTypePropertyList)
if itemProvider.hasItemConformingToTypeIdentifier(propertyList) {
itemProvider.loadItem(forTypeIdentifier: propertyList, options: nil, completionHandler: { (item, error) -> Void in
guard let dictionary = item as? NSDictionary else { return }
OperationQueue.main.addOperation {
if let results = dictionary[NSExtensionJavaScriptPreprocessingResultsKey] as? NSDictionary,
let urlString = results["URL"] as? String,
let pdfString = results["PDF"] as? String,
let title = results["title"] as? String,
let authors = results["authors"] as? String,
let abstract = results["abstract"] as? String,
let year = results["year"] as? String,
let subjects = results["subjects"] as? String,
let url = URL(string: urlString) {
print("URL retrieved: \(urlString)")
print("PDF retrieved: \(pdfString)")
print("Title retrieved: \(title)")
print("Authors retrieved: \(authors)")
print("Abstract retrieved: \(abstract)")
print("Year retrieved: \(year)")
print("Subjects retrieved: \(subjects)")
// TODO: Save the file to a folder, and save the meta-data to the model
let realm = try! Realm()
let article = Article()
article.title = title
article.url = urlString
let ppath = String(urlString.suffix(from: String.Index.init(encodedOffset: 22)))
article.pdfPath = ppath
article.authors = authors
article.subjects = subjects
article.year = year
article.abstract = abstract
try! realm.write {
realm.add(article, update: true)
}
do {
let pdfURL = URL(string: pdfString)
let pdfData = try Data(contentsOf: pdfURL!)
let fileName = String(urlString.suffix(from: String.Index.init(encodedOffset: 22)))
try Disk.save(pdfData, to: .documents, as: "\(fileName).pdf")
} catch {
print("Error")
}
print("Everything went fine.")
}
}
})
} else {
print("error")
}
}
如何通过调用主应用程序来替换保存的部分?另外,即使上面的代码运行正常,共享扩展完成后也会崩溃。
我已经搜索了很多有关Share扩展的信息,但是Apple的文档位于Objective C中,其余教程并未涵盖我的情况。