调用函数并等待其完成
Calling a function and wait for its completion
我有这个class和它的功能
class DataUsuarios {
func update(completionHandler : ((isResponse : Array<JSON>) -> Void)) {
//CODE
completionHandler(isResponse: jsn)
}
}
我用这个来称呼它
let data = DataUsuarios()
data.update{(isResponse) -> Void in
self.datos = isResponse
}
它正常工作..
现在我有了这个 class 和我制作的功能
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
}
希望对您有所帮助! :)
也许你想要 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)
}
}
}
好的,我找到了..
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
}
}
我有这个class和它的功能
class DataUsuarios {
func update(completionHandler : ((isResponse : Array<JSON>) -> Void)) {
//CODE
completionHandler(isResponse: jsn)
}
}
我用这个来称呼它
let data = DataUsuarios()
data.update{(isResponse) -> Void in
self.datos = isResponse
}
它正常工作..
现在我有了这个 class 和我制作的功能
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
}
希望对您有所帮助! :)
也许你想要 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)
}
}
}
好的,我找到了..
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
}
}