我正在使用以下功能在HTTP为我的申请发布JSON请求(上传照片):
static func HTTPPostJSON(url: String,
jsonObj: AnyObject,
callback: (String, String?) -> Void) {
var request = NSMutableURLRequest(URL: NSURL(string: url)!)
request.HTTPMethod = "POST"
request.addValue("application/json",
forHTTPHeaderField: "Content-Type")
let jsonString = JSONStringify(jsonObj)
let data: NSData = jsonString.dataUsingEncoding(
NSUTF8StringEncoding)!
request.HTTPBody = data
HTTPsendRequest(request, callback)
}
jsonStringify:
static func JSONStringify(jsonObj: AnyObject) -> String {
if((jsonObj as? [Dictionary<String, AnyObject>]) != nil || (jsonObj as? [Array<AnyObject>]) != nil){
var e: NSError?
var jsonData = NSJSONSerialization.dataWithJSONObject(jsonObj, options: NSJSONWritingOptions(0), error: &e);
if e != nil {
println(e);
return "\(jsonObj)";
} else {
return NSString(data: jsonData!, encoding: NSUTF8StringEncoding)!
}
} else {
return "\(jsonObj)";
}
}
在这种情况下,回调函数接收参数“Bad Request”,但我不知道它为什么会发生。有没有更好的工作方式来在JSON中发出HTTP照片发布请求?