GPH GPH - 1 month ago 40
iOS Question

UIActivityViewController error after migration to Swift 2

The

ShareButton
function worked in Xcode 6, but it has an error after upgrading to
Xcode 7
in the line:


avc.completionWithItemsHandler = {


My code:

@IBAction func ShareButton(sender: AnyObject) {

let things = ["Thank you"]

let avc = UIActivityViewController(activityItems:things, applicationActivities:nil)

avc.setValue("Salon Job HK", forKey: "subject")

avc.completionWithItemsHandler = {

(s: String!, ok: Bool, items: [AnyObject]!, err:NSError!) -> Void in

}

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

if let pop = avc.popoverPresentationController {

let v = sender as! UIView // sender would be the button view tapped, but could be any view

pop.sourceView = v

pop.sourceRect = v.bounds

}

}

Answer

Just check Swift 2.0 UIActivityViewControllerCompletionWithItemsHandler's declaration:

typealias UIActivityViewControllerCompletionWithItemsHandler = (String?, Bool, [AnyObject]?, NSError?) -> Void

try like this:

avc.completionWithItemsHandler = {

    (s: String?, ok: Bool, items: [AnyObject]?, err:NSError?) -> Void in

}

or simply:

avc.completionWithItemsHandler = {
    (s, ok, items, err) in

} 

Swift 3

@IBAction func ShareButton(sender: AnyObject) {  
    let things = ["Thank you"]
    let avc = UIActivityViewController(activityItems: things, applicationActivities: nil)
    avc.setValue("Salon Job HK", forKey: "subject")
    avc.completionWithItemsHandler = {
        (s, ok, items, error) in

    }
    present(avc, animated: true, completion: nil)
    if let pop = avc.popoverPresentationController {
        let v = sender as! UIView // sender would be the button view tapped, but could be any view
        pop.sourceView = v
        pop.sourceRect = v.bounds

    }
}