我正在尝试使用Swift.org和Alamofire GitHub页面上提供的示例代码使用Alamofire和Swift触发GET请求。显然,请求没有被执行。
环境:
首先,我create a new executable包:
[u@h ~/swift]$ mkdir Foo
[u@h ~/swift]$ cd Foo/
[u@h ~/swift/Foo]$ swift package init --type executable
Creating executable package: Foo
Creating Package.swift
Creating README.md
Creating .gitignore
Creating Sources/
Creating Sources/Foo/main.swift
Creating Tests/
Alamofire在Package.swift
中获得added as a dependency:
// swift-tools-version:4.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "Foo",
dependencies: [
.package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.0.0")
],
targets: [
.target(
name: "Foo",
dependencies: ["Alamofire"]),
]
)
然后我将the example code添加到main.swift
:
import Alamofire
print("Hello, world!")
Alamofire.request("https://httpbin.org/get").responseJSON { response in
print("Request: \(String(describing: response.request))") // original url request
print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)") // response serialization result
if let json = response.result.value {
print("JSON: \(json)") // serialized json response
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)") // original server data as UTF8 string
}
}
print("Goodbye, world!")
之后我尝试运行它:
[u@h ~/swift/Foo]$ swift run
Fetching https://github.com/Alamofire/Alamofire.git
Cloning https://github.com/Alamofire/Alamofire.git
Resolving https://github.com/Alamofire/Alamofire.git at 4.6.0
Compile Swift Module 'Alamofire' (17 sources)
Compile Swift Module 'Foo' (1 sources)
Linking ./.build/x86_64-apple-macosx10.10/debug/Foo
Hello, world!
Goodbye, world!
如您所见,Alamofire示例代码中的print
语句都没有被执行。请求也不会被执行,这可以在Alamofire.request
呼叫指向本地Web服务器时观察到。
我做错了什么?
答案 0 :(得分:4)
使用DispatchGroup
等待网络请求的完成:
import Alamofire
import Foundation
print("Hello, world!")
let group = DispatchGroup()
group.enter()
Alamofire.request("https://httpbin.org/get").responseJSON { response in
// handle the response
group.leave()
}
group.notify(queue: DispatchQueue.main) {
print("Goodbye, world!")
exit(0)
}
dispatchMain()