【发布时间】:2018-12-18 20:46:40
【问题描述】:
Insomnia 生成了一个代码,它可以工作:
import Foundation
let headers = [
"x-auth-header": "fb2f56fde81f21926fc0b5b74702f71da9f152efa7b5587a308984b71c9acac7fd44da05583ab06d57d29794f59fc475d9f2d132cbc6e29c421f11330a30a613",
"content-type": "application/x-www-form-urlencoded"
]
let postData = NSData(data: "".data(using: String.Encoding.utf8)!)
let request = NSMutableURLRequest(url: NSURL(string: "http://rekrutacja.backendzs.pl/note/")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()
它可以工作并且必须返回项目数组:
[
{
"note_id": 14,
"title": "last one",
"content": "maybe",
"version": 16,
"created": 1530825998,
"modified": 1530825998
},
{
"note_id": 13,
"title": "again",
"content": "again",
"version": 15,
"created": 1530825532,
"modified": 1530825532
},
{
"note_id": 12,
"title": "zzz",
"content": "zzzz",
"version": 14,
"created": 1530825484,
"modified": 1530825484
},
{
"note_id": 11,
"title": "Nowy tytuł",
"content": "4",
"version": 13,
"created": 1530825331,
"modified": 1530825331
},
{
"note_id": 10,
"title": "test5",
"content": "test",
"version": 12,
"created": 1530825252,
"modified": 1530825252
},
{
"note_id": 9,
"title": "title7",
"content": "1111",
"version": 11,
"created": 1530825225,
"modified": 1530825225
},
{
"note_id": 7,
"title": "test",
"content": "content",
"version": 9,
"created": 1530817192,
"modified": 1530817192
},
{
"note_id": 6,
"title": "Tytuł",
"content": "Treść",
"version": 8,
"created": 1530550847,
"modified": 1530550847
},
{
"note_id": 5,
"title": "Tytuł",
"content": "Treść",
"version": 7,
"created": 1530547099,
"modified": 1530547099
},
{
"note_id": 3,
"title": "title",
"content": "content",
"version": 3,
"created": 1530469102,
"modified": 1530469102
},
{
"note_id": 2,
"title": "title",
"content": "content",
"version": 2,
"created": 1530468369,
"modified": 1530468369
}
]
但是,它不向该列表提供来自服务器的响应。仅显示一般数据。我已经测试并检查了与 Alamofire、swiftyJSON、Swift .get 请求相关的每篇文章,但它们都不起作用。
考虑到这些信息:
- 正在建立与服务器的连接(代码)
- 如果启动生成的“shell”代码并通过“终端”运行 (Mac OS) 它返回数组。
- 解析不正确?如果是 - 如何提取这些数据?
尝试过字典、swiftyJSON、NSSession ......但我肯定做错了什么。我是第一次在 SWIFT 处理 JSON,所以我可以犯一些愚蠢的错误!
感谢所有愿意提前提供帮助的人!!!
【问题讨论】: