我想从代码中提到的网站获取数据,但是我遇到了一个错误,并且我不知道该怎么做才能解决它。 有谁可以帮助我吗? 谢谢
这些是我使用的代码
@IBAction func onGetTapped(_ sender: Any) {
guard let url = URL(string: "http://gpsforanimal.herokuapp.com/") else { return }
let session = URLSession.shared
session.dataTask(with: url) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
print(data)
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any]
print(json)
} catch {
print(error)
}
}
}.resume()
}
我明白了
<NSHTTPURLResponse: 0x16d47ac0> { URL: http://gpsforanimal.herokuapp.com/ } { status code: 200, headers {
"Cache-Control" = "max-age=0, private, must-revalidate";
Connection = "keep-alive";
"Content-Length" = 17536;
"Content-Type" = "text/html; charset=utf-8";
Date = "Thu, 05 Jul 2018 21:57:30 GMT";
Etag = "W/\"cde6bf7e5688b2395a936b5785c715c4\"";
Server = "WEBrick/1.3.1 (Ruby/2.2.6/2016-11-15)";
"Set-Cookie" = "_GPS_session=MkZTb1NWQmp1QnA5MXFpUHQ3Wk1NdHV6Vm5ESjNGR1M5cC9jMUkxRTFVQXFuU1VTWko0R2F2a29WV3hNMzczcTAzVjB2TmpBTG5QbGFwcUVObnFHTEp5T0J6NWlFNXNBZ1ZJT1M4R3ZxRWthTzV4RUswalk3eDlrME1mc09KRGZlYzhLaGwxSlh1aGVXcDlPaFF4Vi9RPT0tLUNzNHpzUlVHSXFkZ3czZThyZU9ZMlE9PQ%3D%3D--c9fbcde23b38905f956d4a139629c710565d1015; path=/; HttpOnly";
Via = "1.1 vegur";
"X-Content-Type-Options" = nosniff;
"X-Frame-Options" = SAMEORIGIN;
"X-Request-Id" = "c2c9432e-37dd-4f44-9d10-62314f2c8ebc";
"X-Runtime" = "0.040508";
"X-Xss-Protection" = "1; mode=block";
} }
17536 bytes
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x16d63c60 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
答案 0 :(得分:2)
尝试:
func getURL(){
var request = URLRequest(url: URL(string: "http://gpsforanimal.herokuapp.com/positions.json")!)
request.httpMethod = "GET"
let session = URLSession.shared
session.dataTask(with: request) {data, response, error in
if error != nil {
print(error!.localizedDescription)
}
guard let data = data else { return }
do {
//Decode retrived data with JSONDecoder and assing type of Article object
let realData = try JSONDecoder().decode([gps].self, from: data)
print(realData)
} catch let jsonError {
print(jsonError)
}
}.resume()
}
并创建一个带有可编码的结构,如下所示:
struct gps : Codable{
var id = Int()
var longitude : String?
var latitude : String?
var created_at = String()
var updated_at = String()
var url = String()
init(){
self.id = Int()
self.longitude = String()
self.latitude = String()
self.created_at = String()
self.updated_at = String()
self.url = String()
}
}
,然后调用您的函数 getURL()
答案 1 :(得分:2)
对于swift4.1,无需初始化
func getURL(){
var request = URLRequest(url: URL(string: "http://gpsforanimal.herokuapp.com/positions.json")!)
request.httpMethod = "GET"
let session = URLSession.shared
session.dataTask(with: request) {data, response, error in
if error != nil {
print(error!.localizedDescription)
}
guard let data = data else { return }
do {
//Decode retrived data with JSONDecoder and assing type of Article object
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let realData = try decoder.decode([gps].self, from: data)
print(realData)
} catch let jsonError {
print(jsonError)
}
}.resume()
}
创建一个结构:
struct gps : Decodable{
var id :Int
var longitude : String?
var latitude : String?
var createdAt : String
var updatedAt : String
var url : String
}
答案 2 :(得分:0)
您能否将URL更改为http://gpsforanimal.herokuapp.com/positions.json,然后重试;
您提供的URL返回了JSON的表格呈现,您需要提取JSON而不是表格。
答案 3 :(得分:-2)
尝试使用AlamoFire获取数据。您可以使用SwiftyJSON分析并更好地从网站的JSON响应中获取数据。