我正在尝试弄清楚如何将JSON数据存储到变量中以供以后使用。如何存储它,是否可以在另一个视图控制器中使用该变量,或者我是否必须执行另一个请求以获取数据?
这是我的代码:
@IBAction func signinTapped(_ sender: UIButton) {
guard let url = URL(string: "http://XXXXXX/TestReqIOS.php") else {
return
}
let email = txtEmail.text!
let password = txtPassword.text!
let data : Data = "loginSubmit=1&email=\(email)&password=\(password)&grant_type=password".data(using: .utf8)!
var request : URLRequest = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type");
request.setValue(NSLocalizedString("lang", comment: ""), forHTTPHeaderField:"Accept-Language");
request.httpBody = data
print("Calling API")
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// vs let session = URLSession.shared
// make the request
let task = session.dataTask(with: request, completionHandler: {
(data, response, error) in
if let error = error {
print("error")
}
else if let response = response {
print("response")
}
else if let data = data {
print(data)
}
DispatchQueue.main.async { // Correct
guard let responseData = data else {
print("Error: did not receive data")
return
}
print(String(data: responseData, encoding: String.Encoding.utf8) ?? "")
}
})
task.resume()
}
哪个会返回:
{
"id": "7",
"first_name": "John",
"last_name": "Doe",
"email": "JohnDoe@text.com",
"created": "2019-03-11",
"modified": "2019-03-10",
}
答案 0 :(得分:2)
最好使用一个结构,例如您的情况:
struct Data: Codable {
let id: Int
let first_name: String
let last_name: String
let email: String
let created: Date
let modified: Date
}
然后创建该结构的变量,并将其存储在其中:
var dataVariable = [Data]()
然后您可以像这样进行URL呼叫:
func getData(arr: Bool, completion: @escaping (Bool) -> ()) {
let urlJSON = "URL"
guard let url = URL(string: urlJSON) else { return }
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data else { return }
do {
let getData = try JSONDecoder().decode([Data].self, from: data)
self.dataVariable = getData
} catch let jsonErr {
print("error serializing json: \(jsonErr)")
}
completion(arr)
}.resume()
}
然后,您可以从dataVariable变量中访问所有这些内容。如果您在Manager类中执行此操作,则可以从任何ViewController访问它。
要访问:
let firstNameString = dataVariable[0].first_name
如果没有多个相同的树,则只需确保其:
let getData = try JSONDecoder().decode(Data.self, from: data)
编辑:
您的情况如下:
let task = session.dataTask(with: request, completionHandler: {
(data, response, error) in
if let error = error {
print("error")
}
else if let response = response {
print("response")
}
else if let data = data {
let getData = try JSONDecoder().decode([Data].self, from: data)
self.dataVariable = getData // <- Just decode here
print(data)
}
DispatchQueue.main.async { // Correct
guard let responseData = data else {
print("Error: did not receive data")
return
}
print(String(data: responseData, encoding: String.Encoding.utf8) ?? "")
}
})
task.resume()