使用子类UIActivityItemProvider时没有可用的共享操作

时间:2015-02-22 00:48:20

标签: ios swift ios8 uiactivityviewcontroller

当我传入一个NSString时,一切都很完美,但是当我尝试传递我的自定义ItemProvider时,我没有可用的共享操作。

MyCustomProvider

class MyCustomProvider: UIActivityItemProvider {

    var placeholder: String!
    var alternate: String!


    init(placeholder: String, alternate: String) {
        self.placeholder = placeholder
        self.alternate = alternate

        super.init()
    }

    override func activityViewController(activityViewController: UIActivityViewController, itemForActivityType activityType: String) -> AnyObject? {
        if activityType == UIActivityTypeMessage {
            return NSString(string: alternate)
        } else {
            return NSString(string: placeholder)
        }
    }
}

我执行的地方:

var stringToShare = MyCustomProvider(placeholder: "Placeholder", alternate: "Alternate")

var sharingItems = [AnyObject]()
sharingItems.append(stringToShare)

let activityViewController = UIActivityViewController(activityItems: sharingItems, applicationActivities: nil)

activityViewController.excludedActivityTypes = [UIActivityTypePrint, UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll, UIActivityTypeAddToReadingList, UIActivityTypePostToFlickr, UIActivityTypePostToVimeo, UIActivityTypeAirDrop]

self.presentViewController(activityViewController, animated: true, completion: nil)

当上面的stringToShare改为NSString(string: "Placeholder")时,一切都很完美。我在实施中搞砸了什么?

2 个答案:

答案 0 :(得分:2)

我通过以下方式解决了这个问题:

class MyCustomProvider: NSObject, UIActivityItemSource {

    var placeholder: String!
    var alternate: String!


    init(placeholder: String, alternate: String) {
        self.placeholder = placeholder
        self.alternate = alternate

        super.init()
    }

    func activityViewControllerPlaceholderItem(activityViewController: UIActivityViewController) -> AnyObject {
        return NSString(string: placeholder)
    }

    func activityViewController(activityViewController: UIActivityViewController, itemForActivityType activityType: String) -> AnyObject? {
        if activityType == UIActivityTypeMessage {
            return NSString(string: alternate)
        } else {
            return NSString(string: placeholder)
        }
    }
}

我不知道为什么,但它确实有效。

答案 1 :(得分:1)

我相信你必须将placeholderItem设置为你要在item()中返回的类型。

  

可以代表您计划创建的实际对象的对象。对象的内容可能为空,但对象的类必须与您计划稍后提供的对象的类匹配。