我希望我的应用用户使用UIACtivityViewController共享链接。链接不是静态的,我必须从api中获取它。我想在有人按下UIActivityViewController中的图标时立即获取此链接,但我现在如何操作却无法正常工作。请求的完成处理程序始终在方法fetchShareURL()的末尾执行。有人能告诉我如何解决这个问题吗?
import UIKit
class ShareItemSource: NSObject, UIActivityItemSource {
var objects : [AnyObject]?
var shareURL : String?
init(objects : [AnyObject]?){
self.objects = objects
}
func fetchShareURL() -> Bool{
//fetch share url from api
let api = Api()
let semaphore = dispatch_semaphore_create(0);
let backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)
dispatch_async(backgroundQueue, {
api.export(self.groupObjList, receiptObjList: self.receiptObjList){ status, message, url in
dispatch_async(dispatch_get_main_queue(), {
self.shareURL = url
dispatch_semaphore_signal(semaphore);
})
}
});
let delayInSeconds = 30.0;
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds * Double(NSEC_PER_SEC)))
dispatch_semaphore_wait(semaphore, delayTime)
if self.shareURL != nil{
return true
} else {
return false
}
}
@objc func activityViewControllerPlaceholderItem(activityViewController: UIActivityViewController) -> AnyObject {
return ""
}
@objc func activityViewController(activityViewController: UIActivityViewController, itemForActivityType activityType: String) -> AnyObject? {
if fetchShareURL() == true{
return "Download files: "+self.shareURL!
} else {
return nil
}
}
func activityViewController(activityViewController: UIActivityViewController, subjectForActivityType activityType: String?) -> String {
return "title of share"
}
func activityViewController(activityViewController: UIActivityViewController, thumbnailImageForActivityType activityType: String?, suggestedSize size: CGSize) -> UIImage? {
//do stuff
}
}
答案 0 :(得分:0)
如果要在UIActivityView中提供的数据需要时间,请使用UIActivityItemProvider。它是一个NSOperation子类,以完全一致的方式解决整个问题。实际上,这种情况正是它的目的。 (请观看有关高级NSOperation的WWDC 2015视频。)
答案 1 :(得分:0)
暂时将其更改为此内容。后来我会使用NSOperation。
api.export(self.objects){ status, message, url in
if(status == true){
if let url = url{
alert.dismissViewControllerAnimated(true){
let sharingItems = ["Share url", url]
let activityViewController = UIActivityViewController(activityItems: [ShareItemSource(url: url)], applicationActivities: nil)
activityViewController.excludedActivityTypes = [UIActivityTypeAddToReadingList, UIActivityTypeCopyToPasteboard]
self.presentViewController(activityViewController, animated: true, completion: nil)
activityViewController.completionWithItemsHandler = { (activity, success, items, error) in
//Response
}
}
}
} else {
//handle fail
}
}