我有网络服务
http://dev.nsol.sg/projects/sneakers/Api/get_single_news
方法:POST 必需参数:
userid
newsid
响应:
success = 0 (error), 1 (success)
message = Description of result if success = 0 then message will have the detail description
data: if success = 1 then we will have complete details of common requirements like single news
newsurl: News Image URL + Concatenate Value of img from DB
这是我尝试从网址
获取数据func single_news(userid: Int) {
var request = URLRequest(url: URL(string: news_url)!)
request.httpMethod = "POST"
//Pass your parameter here
let postString = "userid=\(userid)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=(error)")
return
}
let json: Any?
do
{
json = try JSONSerialization.jsonObject(with: data, options: [])
print("abcnews")
//here is your JSON
print(json)
}
catch
{
return
}
guard let server_response = json as? NSDictionary else
{
return
}
}
task.resume()
}
如何传递第二个参数newsid。您可以从此链接下载项目https://drive.google.com/file/d/1mBlYcNaW8K3s6Y2V6BY6zdM0Znvyw3Si/view?usp=sharing
答案 0 :(得分:0)
重写你的功能
func single_news(userid: Int , newsid : Int) {}
我认为newsid
也是Int
值。
然后像这样写postString
......
let postString = "userid=\(userid)&newsid=\(newsid)"
我希望这会对你有所帮助。
答案 1 :(得分:0)
如果我理解正确,您只想创建并发送具有两个属性的JSON对象。
你可以这样做:
let body: [String: Any] = ["userid": userid,
"newsid": newsid]
request.httpBody = try! JSONSerialization.data(withJSONObject: body, options: [])