我创建静态var然后发布JSON并用JSON填充它,然后我发布JSON参数,对于param字符串我使用创建的静态var但是当我打印它时它是空的,为什么?
public class SecurityOptions {
static var _TokenID:String! = ""
}
然后我发布Json:
class Security {
func Security () -> String {
let url :NSURL = WebService.tokenWebAddress
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
let paramString = "data=Hello"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
if let responsedata = data {
do{
let json = try NSJSONSerialization.JSONObjectWithData(responsedata, options: NSJSONReadingOptions.AllowFragments)
if let TokenDetail = json as? Dictionary <String,String>
{
SecurityOptions._TokenID = TokenDetail["TokenID"] as String!
}else{
print("KHATA")
}
} catch{
print("not Serialized")
}
}
}.resume()
return SecurityOptions._TokenID
}
}
之后:
let a = Security()
let url :NSURL = WebService.listWebAddress
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
let paramString = ["_TokenID":a.Security()] as Dictionary<String, AnyObject>
request.HTTPMethod = "POST"
let err: NSError?
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(paramString, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request) { data, response, error in
guard data != nil else {
print("no data found: \(error)")
return
}
var index:Int = 0;
do {
var json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
// Okay, the `json` is here, let's get the value for 'success' out of it
if let adsList = json as? Dictionary <String,AnyObject> {
print("success")
} else {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding) // No error thrown, but not NSDictionary
print("Error could not parse JSONs: \(jsonStr)")
}
} catch let parseError {
print(parseError) // Log the error thrown by `JSONObjectWithData`
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
}
}.resume()
当我将参数
用于参数时,我的参数字符串为空