-2

i have this class and its func

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

and i call it with this

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

and it works as it should..

Now i have this class and function that i made

    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()
}
}

but i don't know how to call it and get the completionHandler values

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

}

Hope you can help! :)

Carlos.V
  • 409
  • 6
  • 13
  • What exactly is the problem? "it doesn't work" is definitely not specific enough. – jcaron Dec 02 '15 at 00:38
  • I guess whatever you put in //CODE is running asynchronously. – HMHero Dec 02 '15 at 00:41
  • ok, @jcaron, incorrect syntax calling the function, just says `Consecutive statements on a line must be separated by ';'`, i know how to call the function when it doesn't requiere parameters.. @HMHero, Yes, everything works inside, it was tested before making it a function. – Carlos.V Dec 02 '15 at 00:42
  • You probably want `-> Void` instead of `-> ()` in the definition of you method? – jcaron Dec 02 '15 at 00:45

2 Answers2

0

Perhaps you want dispatch_async()?:

func makeRequest(param : String, url : String, completionHandler : ((succeeded: Bool, msg: String? , crypted : String?) -> ())) {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
        println("This is run on the background queue")
        //CODE
        dispatch_async(dispatch_get_main_queue(), 0), {
            println("This is run on the main queue, after the previous block")
            completionHandler(succeeded: true, msg: nil, crypted: decrypted)
        }
    }
}
i_am_jorf
  • 53,608
  • 15
  • 131
  • 222
  • Thanks for your answer! I have that under control, my problem is calling the function and wait for `completitionHandler` values.. – Carlos.V Dec 02 '15 at 00:38
0

Ok, i found it..

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
            }
        }
Carlos.V
  • 409
  • 6
  • 13