我有這個類及其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
}
希望能幫到你! :)
到底是什麼問題? 「它不起作用」絕對不夠具體。 – jcaron
我猜無論你放在// CODE中是不是異步運行。 – HMHero
ok,@jcaron,調用函數的語法不正確,只是說'連續的語句在一行上必須用';'分開,我知道如何在不需要參數時調用該函數.. @HHHero,是,一切都在裏面工作,它在進行功能測試之前已經過測試。 –