【发布时间】:2019-02-10 23:11:09
【问题描述】:
使用 Swift 4 和 Xcode 10
我正在尝试向 API 发出 GET 请求并以 json 格式获取结果,并且我的代码在我的操场上运行良好,但是当我将其复制到我的应用程序时,我得到一个“程序以退出代码结束: 0" 错误。
我想让这个函数成为我可以调用的函数,并更改标头、httpMethod、凭据、actionURL 等。这样我就可以将它重用于对该 API 的不同调用。
这是我第一次尝试,并且一直在寻找。
1) 这是我为这部分项目借用的大部分代码的地方。 Error parsing JSON in swift and loop in array
2) 我尝试使用此视频中的建议来构建数据结构。 https://www.youtube.com/watch?v=WwT2EyAVLmI&t=105s
不确定是 swift 端还是 xcode 端...
import Foundation
import Cocoa
// removed in project, works in playgrounds
//import PlaygroundSupport
func makeGetCall() {
// Set up the URL request
let baseURL: String = "https://ws.example.net/v1/action"
guard let url = URL(string: baseURL) else {
print("Error: cannot create URL")
return
}
// set up the session
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// set up auth
let token = "MYTOKEN"
let key = "MYKEY"
let loginString = String(format: "%@:%@", token, key)
let loginData = loginString.data(using: String.Encoding.utf8)?.base64EncodedString()
// make the request
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("Basic \(loginData!)", forHTTPHeaderField: "Authorization")
let task = session.dataTask(with: request) {
(data, response, error) in
// check for any errors
guard error == nil else {
print("error calling GET")
print(error!)
return
}
// make sure we got data
guard let responseData = data else {
print("Error: did not receive data")
return
}
// parse the result as JSON, since that's what the API provides
do {
guard let apiResponse = try JSONSerialization.jsonObject(with: responseData, options: [])
as? [String: Any] else {
print("error trying to convert data to JSON")
return
}
// let's just print it to prove we can access it
print(apiResponse)
// the apiResponse object is a dictionary
// so we just access the title using the "title" key
// so check for a title and print it if we have one
//guard let todoTitle = todo["title"] as? String else {
// print("Could not get todo title from JSON")
// return
//}
//print("The title is: " + todoTitle)
} catch {
print("error trying to convert data to JSON")
return
}
}
task.resume()
}
makeGetCall()
// removed in project, works in playgrounds
//PlaygroundPage.current.needsIndefiniteExecution = true
在 Playgrounds 中,我收到了预期的 json 响应,但是当我将代码复制到我的项目时,我收到了一个错误。
预期输出示例:
["facet": <__NSArrayI 0x7fb4305d1b40>(
asnNumber,
assetPriority,
assetType,
etc...
【问题讨论】: