【发布时间】:2020-06-08 00:16:24
【问题描述】:
在下面的代码中,我可以通过这种方式读取文本并打印代码中的文本。
但是我不知道怎么把txt文件作为附件分享出来,用下面的代码读出来。
import UIKit
import Social
import CoreServices
class ShareViewController: SLComposeServiceViewController {
private var textString: String?
override func isContentValid() -> Bool {
// Do validation of contentText and/or NSExtensionContext attachments here
if textString != nil {
if !contentText.isEmpty {
return true
}
}
return true
}
override func viewDidLoad() {
super.viewDidLoad()
let extensionItem = extensionContext?.inputItems[0] as! NSExtensionItem
let contentTypeText = kUTTypeText as String
for attachment in extensionItem.attachments! {
if attachment.isText {
attachment.loadItem(forTypeIdentifier: contentTypeText, options: nil, completionHandler: { (results, error) in
let text = results as! String
self.textString = text
_ = self.isContentValid()
})
}
}
}
override func didSelectPost() {
// This is called after the user selects Post. Do the upload of contentText and/or NSExtensionContext attachments.
print(String(textString!)) // <-- I cannot read txt file and print it
// 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 []
}
}
//MARK: NSItemProvider check
extension NSItemProvider {
var isText: Bool {
return hasItemConformingToTypeIdentifier(kUTTypeText as String)
}
}
有什么方法可以将txt文件作为附件分享到Share Extension中吗?
感谢您的帮助。
【问题讨论】:
-
所以现在你在问“如何编写共享扩展”?
-
我粘贴的代码可以分享文字为图片。但我想分享一个完整的 txt 文件并阅读它。我没有搜索任何类似的代码。
标签: swift share-extension