如何在服务器中使用Array并在服务中显示
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在服务器中使用Array并在服务中显示相关的知识,希望对你有一定的参考价值。
我使用POST METHOD从服务器获得此响应
{
"jsonrpc": "2.0",
"id": null,
"result": [
"alaa",
"belal",
"demo"
"mohanad"
]
}
如何将数据导入服务器并保存在模型中?这是我使用Alamofire
的服务器请求
class servicedb: NSObject{
class func dbs (completion: @escaping (_ error: Error?, _ db: ([Database]))->Void){
let url = "http://176.58.117.249/web/database/list"
let header = ["Content-Type" : "application/json"]
Alamofire.request(url, method: .post, parameters: nil, encoding: URLEncoding.default, headers:header)
.responseJSON{ response in
switch response.result
{
case.failure(let error):
print (error)
case .success(let value):
let json = JSON(value)
guard let results = json ["result"].array else
{ return }
var dbs = [Database]()
for data in results {
guard let data = data.dictionary else {
return }
let datab = Database()
datab.result = data["result"]?.string ?? ""
dbs.append(datab)
}
completion(nil,dbs)
}
}
}
}
我的数据模型是保存数据
class Database: NSObject {
var id: Int = 0
var result : String = ""
}
响应不会出现在我的Web服务中,也不会将数据存储在数据模型中。提前致谢
答案
在您的Web服务中传递parameter
作为nil
然后给一个文件管理器并传递为String
"{}"
给出成功响应。
您的网络服务响应在[String]
,所以您可以这样使用。
class func dbs (completion: @escaping (_ error: Error?, _ db: ([String]))->Void){
let url = "http://176.58.117.249/web/database/list"
let header: [String:String] = ["Content-Type" : "application/json"]
let parameters = [:] as [String : Any]
do {
let postData = try JSONSerialization.data(withJSONObject: parameters, options: [])
let urlStr = URL(string: url)
let urlRequest = URLRequest(url: urlStr!)
var request = try URLEncoding.queryString.encode(urlRequest, with: parameters)
request.httpMethod = "POST"
request.httpBody = postData as Data
for headerValue in header{
request.addValue(headerValue.value, forHTTPHeaderField: headerValue.key)
}
Alamofire.request(request).responseJSON{ response in
switch response.result
{
case.failure(let error):
print (error)
case .success(let value):
let json = JSON(value)
guard let results = json ["result"].array else
{ return }
var dbs = [String]()
for data in results {
dbs.append(data.string ?? "")
}
completion(nil,dbs)
}
}
}
catch let error{
print(error.localizedDescription)
}
}
以上是关于如何在服务器中使用Array并在服务中显示的主要内容,如果未能解决你的问题,请参考以下文章