afnetworking post方法在objective-c中工作正常,但很快显示参数丢失
let request = NSMutableURLRequest(url: NSURL(string:"apiurl" )! as URL)
let session = URLSession.shared request.httpMethod = "POST"
let params = ["appId":"1","deviceId":"1","deviceToken":"1"] as Dictionary<String, String>
request.httpBody = try! JSONSerialization.data(withJSONObject: params, options: [])
let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
print("Response: \(response)")})
task.resume()
最佳答案
您可以使用以下一种:
func HTTPsendRequest(request: NSMutableURLRequest,
callback: @escaping (String, String?) -> Void) {
let task = URLSession.shared
.dataTask(with: request as URLRequest) {
(data, response, error) -> Void in
if (error != nil) {
callback("", error?.localizedDescription)
} else {
callback(NSString(data: data!,
encoding: String.Encoding.utf8.rawValue)! as String, nil)
}
}
task.resume()
}
func HTTPPostJSON(url: String, data: NSData,
callback: @escaping (String, String?) -> Void) {
let request = NSMutableURLRequest(url: NSURL(string: url) as! URL)
print("",request)
request.httpMethod = "POST"
request.addValue("application/json",forHTTPHeaderField: "Content-Type")
request.addValue("application/json",forHTTPHeaderField: "Accept")
request.httpBody = data as Data
HTTPsendRequest(request: request, callback: callback)
}
/////how to use:
func example() {
let url = "apiurl"
let para:NSMutableDictionary = NSMutableDictionary()
para.setValue("1", forKey: "appId")
para.setValue("1", forKey: "deviceId")
para.setValue("1", forKey: "deviceToken")
print(para)
do {
let jsonData = try JSONSerialization.data(withJSONObject: para, options: .prettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data
let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
// here "decoded" is of type `Any`, decoded from JSON data
// you can now cast it with the right type
if decoded is [String:String] {
// use dictFromJSON
HTTPPostJSON(url: url, data:jsonData as NSData) { (response, error) -> Void in
print(response);
//here is the response
}
}
} catch {
print(error.localizedDescription)
}
}
关于swift - afnetworking post方法在objective-c中工作正常,但很快显示参数丢失,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42368546/