我从事项目,我必须从 php 服务器接收数据。一切正常,只有两件事:1.)无法解析日期。我知道这个问题在这里得到了回答,但在我的情况下没有一个变体起作用。这是我的代码
import Foundation
import SwiftyJSON
func getClientDataFromServer(id: String?) {
guard let id = id else {return}
let jsonUrlString = "https://sverlim.software/cms/clientReadOneClient.php?client_id=10"
let url = URL(string: jsonUrlString)!
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard err == nil else {
print(err!.localizedDescription)
return
}
print(response as Any)
guard let data = data else {return}
let dateFormatterWithTime: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
formatter.timeZone = TimeZone(abbreviation: "UTC")
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
let datastring = String(data: data, encoding: .utf8)
print("data====\(datastring!)")
let json = try! JSONSerialization.jsonObject(with: data, options: []) as! [[String:Any]]
print(json[0]["datarteg"] as Any)
do {
let decoder = JSONDecoder()
let object = try! JSON(data: data)
print(object[0]["datareg"].dateTime)
print(object[0]["company"].stringValue)
decoder.dateDecodingStrategy = .formatted(dateFormatterWithTime)
let clients = try decoder.decode([Client].self, from: data)
print(clients)
let client = clients.first
print(client!)
} catch let jsonErr {
print(jsonErr)
}
}.resume()
}
struct Client: Codable {
let id: String?
let name: String?
let phone: String?
let company: String?
let discount: String?
var datareg: Date?
}
class Formatter {
static let jsonDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
static let jsonDateTimeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss"
return formatter
}()
}
extension JSON {
public var date: Date? {
get {
switch self.type {
case .string:
return Formatter.jsonDateFormatter.date(from: self.object as! String)
default:
return nil
}
}
}
public var dateTime: Date? {
get {
switch self.type {
case .string:
return Formatter.jsonDateTimeFormatter.date(from: self.object as! String)
default:
return nil
}
}
}
我跟着这个答案
Swift 的 JSONDecoder 在 JSON 字符串中有多种日期格式?
https://useyourloaf.com/blog/swift-codable-with-custom-dates/
这是我从日志中打印的内容
data====
[{"id":"10","name":"\u0423\u043a\u0440\u0430\u0438\u043d\u0435\u0446
\u0410\u043b\u0435\u043a\u0441\u0430\u043d\u0434\u0440","phone":"+38098497
4673","company":"2","discount":"0","datereg":"2017-11-28 14:16:16"}]
nil
nil
2
[SashaApp.Client(id: Optional("10"), name: Optional("Украинец Александр"),
phone: Optional("+380984974673"), company: Optional("2"), discount:
Optional("0"), datareg: nil)]
Client(id: Optional("10"), name: Optional("Украинец Александр"), phone:
Optional("+380984974673"), company: Optional("2"), discount:
Optional("0"), datareg: nil)
正如我们所看到的,数据包含“datareg”字段,但是在解析后无论如何(JSONDecoder,JSONSerialization,SwiftyJSON)我收到 nil 2)SSL_ERROR_ZERO_RETURN(6)
伙计们将不胜感激任何帮助。谢谢))