如何让任务在 Swift 3 中等待完成

How do I make task wait for completion in Swift 3

我正在使用 Alamofire 向 HTTP 服务器发送登录请求。它 returns 一个 JSON 响应。我的问题是主线代码在 .responseJSON 之前完成。如何等到响应返回后才从函数返回?

var ret: Bool = true
Alamofire.request(
        URL(string: "http://localhost:8081/login/iPhone")!,
        method: .post,
        parameters: ["email":"test@test.test", "password":"test", "uuid":String(describing: UIDevice.current.identifierForVendor!.uuidString)],
        headers: [:])
    .validate()
    .responseJSON{(response) -> Void in
        do {
            guard response.result.isSuccess else {
                throw FieldError.fetchError(responseError: response.result.error)
            }
            guard let value = response.result.value as? [String: Any],
                    let status = value["status"] as? String,
                    let message = value["message"] as? String else {
                throw FieldError.messageFormatError
            }
            switch status {
                case "Login suggess":
                    break
                default:
                    throw FieldError.fieldServerError(status: status, message: message)
            }
        } catch {
            ret = false
            debugPrint(error)
        }
    }
return ret

您始终可以使用全局

typealias DownloadComplete = () -> ()

下一个和你一起玩的是 json

func yourFunc(completed: @escaping DownloadComplete)

下载后使用

completed()