调用函数并等待其完成

时间:2015-12-02 00:31:52

标签: ios swift func

我有这个类及其功能

class DataUsuarios {    
    func update(completionHandler : ((isResponse : Array<JSON>) -> Void)) {
       //CODE
       completionHandler(isResponse: jsn)
    }
}

我用这个叫

let data = DataUsuarios()
data.update{(isResponse) -> Void in
    self.datos = isResponse
}

它可以正常工作..

现在我有了这个类和功能,我做了

    import Foundation

class Post{
func makeRequest(param : String, url : String, completionHandler : ((succeeded: Bool, msg: String? , crypted : String?) -> Void)) {
    let request = NSMutableURLRequest(URL: NSURL(string: url)!)
    let params : Dictionary<String, String> = ["VAL": param]
    let session = NSURLSession.sharedSession()
    session.configuration.timeoutIntervalForRequest = 3 //3 segundos timeoutRequest
    session.configuration.timeoutIntervalForResource = 5 //5 segundos timeoutResource
    request.HTTPMethod = "POST"

    do{
        request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)
    }catch let err as NSError {
        print(err.localizedDescription)
        print("Error could not make request'")
        completionHandler(succeeded: false, msg: "Error al interpretar JSON" , crypted: nil)

    }
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        print("Response: \(response)")
        let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("Body: \(strData)")
        var json : NSDictionary?
        do{
            json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
        }catch let err as NSError {
            print(err.localizedDescription)
            let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("Error could not parse JSON: '\(jsonStr)'")
            completionHandler(succeeded: false, msg: "Error en POST", crypted: nil)

        }
        if let parseJSON = json {

            if let encrypted = parseJSON["encriptado"] as? String {
                let decrypted = encrypted.aesDecrypt()
                let datosDecrypted: NSData = decrypted.dataUsingEncoding(NSUTF8StringEncoding)!
                var jsonLogin:NSDictionary!
                do{
                    jsonLogin = try NSJSONSerialization.JSONObjectWithData(datosDecrypted , options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary
                }catch let err as NSError {
                    print(err.localizedDescription)
                    print("Error could not make request'")
                    completionHandler(succeeded: false, msg: "Error" , crypted: nil)

                }
                if ( jsonLogin.valueForKey("success") != nil ) {
                    if let successNumber = jsonLogin.valueForKey("success") as! Int! {

                        print("Success: " , successNumber);
                        completionHandler(succeeded: true, msg: nil, crypted: decrypted)
                    }
                }
                completionHandler(succeeded: false, msg: "Error Success", crypted: nil)
            }
        }
        else {
            // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
            let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("Error could not parse JSON: \(jsonStr)")
            completionHandler(succeeded: false, msg: "Error", crypted:  nil)
        }

    })

    task.resume()
}
}

但我不知道如何调用它并获得completionHandler值

let post = Post()
post.makeRequest(cad, url: Constants.Static.server+"url.php" { succeeded, msg, crypted) -> Void in

}

希望你能帮忙! :)

2 个答案:

答案 0 :(得分:0)

也许你想要dispatch_async()?:

Dim ar as Range, row As Range, rng As Range

Ws.ShowAllData  'Remove All Filters 
lastrow_ = ws.Range("A" & Rows.Count).End(xlUp).row
Ws.Range("A2" & lastrow_).AutoFilter Field:=1, Criteria1:="=1" 'Filter on the Criteria

'Set The Range
Set rng = ws.Range("A1:P" & Cells(Rows.Count,"A").End(xlUp).row).SpecialCells(xlCellTypeVisible)

'Loop through the range
For Each ar in rng.Areas
For Each row in ar.Rows
    'do stuff
Next row, ar

答案 1 :(得分:0)

好的,我找到了..

post.makeRequest(cad, url: Constants.Static.server+"url.php" ){(succedded : Bool, msg : String?, crypted:String? ) in
            if(succedded){
                // CODE USING CRYPTED
            }else {
                // CODE USING MSG
            }
        }