gpt4 book ai didi

swift - Alamofire 请求在 Swift 4 项目中不起作用

转载 作者:搜寻专家 更新时间:2023-11-01 06:14:07 27 4
gpt4 key购买 nike

我正在尝试使用 Swift.org 和 Alamofire GitHub 页面上提供的示例代码使用 Alamofire 和 Swift 触发 GET 请求。显然,请求没有得到执行。

环境:

  • macOS 10.13.3
  • swift 4.0.3
  • Alamofire 4.6.0
  • Xcode 9.2

首先,我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 获得 added as a dependencyPackage.swift 中:

// 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 codemain.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 服务器时可以观察到这一点。

我做错了什么?

最佳答案

使用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()

关于swift - Alamofire 请求在 Swift 4 项目中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48720001/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com