使用 swift 4 发出 GET 请求在操场上有效,但在项目中无效
Making a GET request with swift 4 works in playgrounds but not in project
使用 Swift 4 和 Xcode 10
我正在尝试向 API 发出 GET 请求并在 json 中获取结果,并且我的代码在我的操场上完美运行,但是当我将其复制到我的应用程序时,我收到 "Program ended with exit code: 0" 错误。
我想让这个函数成为我可以调用和更改 headers、httpMethod、凭据、actionURL 等的函数。这样我就可以在对这个 [=36= 的不同调用中重复使用它].
这是我的第一次尝试,并且一直在寻找。
1) 这部分项目的大部分代码都是在这里借用的。
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
在操场上,我收到了预期的 json 响应,但是当我将代码复制到我的项目时,我收到了一个错误。
预期输出示例:
["facet": <__NSArrayI 0x7fb4305d1b40>(
asnNumber,
assetPriority,
assetType,
etc...
"Program ended with exit code: 0" 不是错误;这只是意味着程序结束了。事实上,它与错误相反,因为它意味着程序已经结束井井有条。
那么,你用的是什么项目模板呢?我猜您使用了 Cocoa 命令行工具。在那种情况下,问题是你没有运行循环,所以我们到达最后一行并在任何异步内容(例如网络)发生之前结束。
这与您在操场上所做的完全相同。没有 needsIndefiniteExecution
就无法异步联网;游乐场在到达最后一行后需要保持 运行,以便让网络有机会发生。同样的,你需要命令行工具中的runloop在运行到最后一行后继续运行,让网络有机会发生。
有关如何为您的命令行工具提供运行循环的信息,请参见 Run NSRunLoop in a Cocoa command-line program
示例
或者,不要使用命令行工具。制作一个实际的 app。现在该应用程序仍然存在(直到您退出它),并且异步网络正常工作。
使用 Swift 4 和 Xcode 10
我正在尝试向 API 发出 GET 请求并在 json 中获取结果,并且我的代码在我的操场上完美运行,但是当我将其复制到我的应用程序时,我收到 "Program ended with exit code: 0" 错误。
我想让这个函数成为我可以调用和更改 headers、httpMethod、凭据、actionURL 等的函数。这样我就可以在对这个 [=36= 的不同调用中重复使用它].
这是我的第一次尝试,并且一直在寻找。
1) 这部分项目的大部分代码都是在这里借用的。
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
在操场上,我收到了预期的 json 响应,但是当我将代码复制到我的项目时,我收到了一个错误。
预期输出示例:
["facet": <__NSArrayI 0x7fb4305d1b40>(
asnNumber,
assetPriority,
assetType,
etc...
"Program ended with exit code: 0" 不是错误;这只是意味着程序结束了。事实上,它与错误相反,因为它意味着程序已经结束井井有条。
那么,你用的是什么项目模板呢?我猜您使用了 Cocoa 命令行工具。在那种情况下,问题是你没有运行循环,所以我们到达最后一行并在任何异步内容(例如网络)发生之前结束。
这与您在操场上所做的完全相同。没有 needsIndefiniteExecution
就无法异步联网;游乐场在到达最后一行后需要保持 运行,以便让网络有机会发生。同样的,你需要命令行工具中的runloop在运行到最后一行后继续运行,让网络有机会发生。
有关如何为您的命令行工具提供运行循环的信息,请参见 Run NSRunLoop in a Cocoa command-line program
示例或者,不要使用命令行工具。制作一个实际的 app。现在该应用程序仍然存在(直到您退出它),并且异步网络正常工作。