how can I call CompletionHandler method?

时间:2018-07-24 10:09:18

标签: swift

I have already created a method but do not know how to pass parameter and manage response parameter.

class func postWithURL(serverlink:String, methodname:String, param:NSDictionary, key:String,  CompletionHandler : @escaping  (Bool,NSDictionary) -> ())

thanks

2 个答案:

答案 0 :(得分:1)

Example of completion method :

func sampleCompletionMethod(name: String, completion:@escaping(Bool)->()) {
    DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
        completion(true)
    }
}

This how you call it :

sampleCompletionMethod(name: "Abc") { (result) in
    print("Result of completion : \(result)")
}

You method should be without class keyword like this :

func postWithURL(serverlink:String, methodname:String, param:NSDictionary, key:String, CompletionHandler : @escaping (Bool,NSDictionary) -> ()) {

}

If your function is in some another class, then make an object of that class, for example if class name is NetworkHelper then add NetworkHelper() to call it.

Call it like this :

postWithURL(serverlink: "link", methodname: "POST", param: NSDictionary(), key: "key") { (boolResutl, dictionay) in

}

Edit: Suggested by Prashant Tukadiya

using NSDictionary is bad practice in swift 4. You should use Swift's Native class of Dictionary

答案 1 :(得分:0)

Here is how you can call your method:

self.postWithURL(serverlink: "link", methodname: "name", param:NSDictionary(), key: "key") { (bool, dictionary) in
            // you code goes here
        }