Я новичок в программировании Swift.Я должен отправить ниже запрос JSON на сервер, используя httpRequest в Swift3.
{
"CompanyId": 162,
"RollupYear": 2018,
"UserId": 1609,
"datarollup": [{
"Name": "Thank You Cards",
"RollupYear": 2018,
"DataRollupColumnID": 210,
"CurrentValue": 520
},
{
"Name": "Prospecting Calls",
"RollupYear": 2018,
"DataRollupColumnID": 212,
"CurrentValue": 1300
}
],
"Seasonalitylist": [{
"CompanyPeriodId": 386,
"UserId": 1609,
"Seasonality": 25
},
{
"CompanyPeriodId": 387,
"UserId": 1609,
"Seasonality": 25
}
]
}
Итак, чтобы отправить JSON в этом формате, я создал Entity Class с именем 'RequestModel':
import Foundation
class RequestModel {
var CompanyId: Int? = 0
var RollupYear: Int? = 0
var UserId: Int? = 0
var dataRollupArr = NSMutableArray()
var seasonalityArr = NSMutableArray()
}
class DataRollupModel {
var Name: String? = ""
var CurrentValue: Float? = 0.0
var RollupYear: Int? = 0
var DataRollupColumnID: Int? = 0
}
class SeasonalityModel {
var CompanyPeriodId: Int? = 0
var UserId: Int? = 0
var Seasonality: Int? = 0
}
У меня есть все мои значения. Может ли кто-нибудь подсказать мне, как добавить значения моих сущностей в требуемый JSON.
Примечание:
Вот мой код для отправки запроса JSON на сервер для входа в систему.:
func login(email:String, password:String, completion:@escaping (NSDictionary) -> ()) {
if let url = NSURL(string: baseurl+"login") {
let request = NSMutableURLRequest( url: url as URL)
let signInDict = ["UserName":email,"Password":password]
print(signInDict)
let jsonData = try! JSONSerialization.data(withJSONObject: signInDict, options: JSONSerialization.WritingOptions.init(rawValue: 0))
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("732rguiqfw9237ryu4k2141", forHTTPHeaderField: "KEY")
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
do{
if let data = data,
let jsonString = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
, error == nil {
completion(jsonString)
} else {
print("error=\(error!.localizedDescription)")
let errorDict = ["error_status":true,"message":error!.localizedDescription] as [String : Any]
completion(errorDict as NSDictionary)
}
}
catch{
print("error=\(error.localizedDescription)")
let errorDict = ["error_status":true,"message":error.localizedDescription] as [String : Any]
completion(errorDict as NSDictionary)
}
}
task.resume()
}
}