user979331 user979331 - 3 months ago 8
iOS Question

Swift Pass parameters in a selector

I have this method here:

func displayPDF(dataParam: NSData, PDFFileParam: String)


Now I am trying to call this method via selector like so:

NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: #selector(FileBrowser.displayPDF(_:PDFFileParam:)), userInfo: nil, repeats: false)


I have these two variables:

let PDFFile = self.data[indexPath.row]["Name"]!!.componentsSeparatedByString("\\").last

var data: NSData!


I would like to use these variables to pass to the method with the selector, how do I do this?

Answer

For that you need to create custom subclass of NSTimer or other way is you can use that userInfo, property of NSTimer like this way.

First change your scheduledTimerWithTimeInterval like this way.

let dic:[String:AnyObject] = ["pdfName" : PDFFile, "pdfData" : data]
NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: #selector(FileBrowser.displayPDF(_:)), userInfo: dic as! AnyObject, repeats: false)

Now change your timer function displayPDF like this.

func displayPDF(timer:NSTimer) {
    if let userInfo = timer.userInfo as? [String: AnyObject] {
         print(userInfo["pdfName"])
    }
}
Comments