我正在尝试通过以下参数快速发出获取请求
var dict = [
"id_struttura" : 2,
"prenCheck" : [
"codice" : "14:30_15:20_1_3831_0",
"id_sport" : 6,
"ora_fine" : "20/02/2015 15:20:00",
"ora_inizio" : "20/02/2015 14:30:00",
"rec" : 0,
"soci" : [
[
"esterno" : 0,
"id" : "1980"
],
[
"esterno" : 0,
"id" : "51"
]
]
]
]
使用以下方法:
private func genericRequest(method: Methods, url: String, data: [String: AnyObject]?) -> AnyObject?{
var getRequest : NSURLRequest?
var postRequest : NSMutableURLRequest?
if method == Methods.GET{
var completeUrl = url
if(data != nil){
//println(data)
completeUrl += "?"
for (key, value) in data! {
completeUrl += "\(key)=\(value)&"
}
completeUrl = completeUrl.substringToIndex(completeUrl.endIndex.predecessor())
}
//println(completeUrl)
let url = NSURL(string: completeUrl)
getRequest = NSURLRequest(URL: url!)
}else if method == Methods.POST{
postRequest = NSMutableURLRequest(URL: NSURL(string: url)!)
var session = NSURLSession.sharedSession()
postRequest!.HTTPMethod = "POST"
var params : String = ""
for (key, value) in data! {
params += "\(key)=\(value)&"
}
params = params.substringToIndex(params.endIndex.predecessor())
var err: NSError?
postRequest!.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding);
}
var response: NSURLResponse? = nil
var error: NSError? = nil
var request = getRequest != nil ? getRequest! : postRequest!
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error)
//println((response as NSHTTPURLResponse).statusCode)
let results = NSString(data:reply!, encoding:NSUTF8StringEncoding)
var json: AnyObject? = convertDataToJSON(reply)
return json
}
将其称为(因为 Method 只是一个枚举)它在发出 get 请求时genericRequest(Method.GET ,url:url, data: dict)
无法解开 data 变量,但在发出 post 请求时可以。for (key,value)in data!
由于我只能使用获取此任务的请求(我正在处理一个糟糕的休息界面),有人可以帮助我吗?
更新:我也试过了if let data = data { ...
,它在这条线上崩溃了 unexpectedly found nil while unwrapping an Optional value