2016-09-29 56 views
0

當我用AFNetworking來發布參數是NSMutableDictionary時,這個請求成功了。在NSURLSession中HTTPBody必須是NSData?

但是當我使用NSURLSession時,self.request!.HTTPBody必須是NSData,所以請求失敗。

如何使用NSURLSession使請求成功?

postDict[@"jgId"] = "1000000000"; 
[manager GET:SELECTDEPART parameters:postDict success:^(AFHTTPRequestOperation *operation, id responseObject) { 

} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    NSLog(@"-----%@", error); 
}]; 

//use NSData 

NSJSONSerialization.dataWithJSONObject(postDict, options: NSJSONWritingOptions.PrettyPrinted) 

請幫幫我。

回答

0
let params = ["jgId": "1000000000"] 
let data = try? JSONSerialization.data(withJSONObject: params, options: [JSONSerialization.WritingOptions(rawValue: 0)]) 

var request = URLRequest(url: URL(string: "https://my-url.com")!, cachePolicy: .returnCacheDataElseLoad, timeoutInterval: 30) 
request.httpMethod = "POST" 
request.httpBody = data 
request.allHTTPHeaderFields = [:] 

URLSession.shared.dataTask(with: request) { (data, response, error) in 

} 
+0

你需要給答案目標C不迅速,因爲OP正與的OBJ C. –

0

您正在使用GET方法向服務器請求數據,因此您的參數不會通過請求HTTPBody數據發送。你的參數很簡單,通過請求URL過去。

問題您有SELECTDEPART作爲請求的基本URL,postDict作爲參數。下面的代碼使用NSURLSession使GET要求與parameters