我的目标是调用一个http服务,该服务返回一个要解析为NewsModel对象数组的json。
我定义了这样的结构
struct NewsModel: Decodable {
var id: Int
var title: String
var content: String
}
并在 Service.swift 类中编写了此方法:
func getNews(pageSize: Int, pageCount: Int, completion: @escaping ([NewsModel]?) -> ()) {
guard let url = URL(string: "\(Service.baseURLSSMService)/news?pageSize=\(pageSize)&pageCount=\(pageCount)") else {return}
var retVal = [NewsModel]()
// Create URLRequest
var request = URLRequest(url: url)
// Set headers and http method
request.httpMethod = "GET"
request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
completion(nil)
return }
do{
print("RESPONSE:\(response.debugDescription)")
retVal = try
JSONDecoder().decode([NewsModel].self, from: dataResponse)
completion(retVal)
} catch let parsingError {
print("Error", parsingError)
completion(nil)
}
}
task.resume()
}
我需要从我的 HomeViewController 调用此方法。我在viewDidLoad中使用了这段代码:
Service.sharedInstance.getNews(pageSize: 10, pageCount: 1) { (news) in
// I need the first element of the news array
// I save it into a global variable
self.homeNews = news?.first
DispatchQueue.main.async {
if self.homeNews != nil {
self.myLabel.text = self.homeNews?.title
}
else {
self.myLabel.text = "No data received."
}
}
}
运行代码时,总是会发生getNews函数返回0个字节的情况,因此JSONDecoder无法解析任何内容。这是错误消息:
错误dataCorrupted(Swift.DecodingError.Context(codingPath:[], debugDescription:“给定的数据不是有效的JSON。”, 底层错误:可选(错误域= NSCocoaErrorDomain代码= 3840 “没有价值。” UserInfo = {NSDebugDescription =无值。})))
如果我上次调用它两次时收到了正确的值。我究竟做错了什么?因为我想我做错了什么,但我做不到。
编辑1 :
这是一个json示例:
[
{
"id": 2048,
"title": "title-sample-1",
"content": "content-sample-1"
},
{
"id": 2047,
"title": "title-sample-2",
"content": "content-sample-2"
}
]
编辑2 :
这是response.debugDescription
RESPONSE:Optional(<NSHTTPURLResponse: 0x2830a1160> { URL: http://.../news?pageSize=1&pageCount=1 } { Status Code: 400, Headers {
Connection = (
close
);
Date = (
"Tue, 27 Nov 2018 15:38:38 GMT"
);
"Transfer-Encoding" = (
Identity
); } })