【问题标题】:Alamofire request not working in Swift 4 projectAlamofire 请求在 Swift 4 项目中不起作用
【发布时间】:2018-07-21 01:26:53
【问题描述】:

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

环境:

  • macOS 10.13.3
  • 斯威夫特 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 在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服务器时可以观察到。

我做错了什么?

【问题讨论】:

    标签: swift alamofire


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-02
      • 1970-01-01
      • 1970-01-01
      • 2019-06-14
      • 1970-01-01
      • 2019-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多