[英]Alamofire return empty response in Mac os command line app
我不知道为什么我的代码无法正常工作。 我创建了网址,并尝试通过Alamofire获得响应。 网址是正确的,它以Postman提供数据。
代码是:
static func getRepolist(request: URLRequest?,
completion: ([String]) -> ()) {
guard let request = request else { return }
Alamofire.request(request)
.validate()
.responseJSON { (response) in
print(response)
}
}
请求是(从控制台中的po request
中获取的):
▿ https://api.github.com/search/users?q=srdanrasic
▿ url : Optional<URL>
▿ some : https://api.github.com/search/users?q=srdanrasic
- cachePolicy : 0
- timeoutInterval : 60.0
- mainDocumentURL : nil
- networkServiceType : __ObjC.NSURLRequest.NetworkServiceType
- allowsCellularAccess : true
▿ httpMethod : Optional<String>
- some : "GET"
▿ allHTTPHeaderFields : Optional<Dictionary<String, String>>
- some : 0 elements
- httpBody : nil
- httpBodyStream : nil
- httpShouldHandleCookies : true
- httpShouldUsePipelining : false
为什么不打印任何内容? 它不在完成块中。 它只是在日志中告诉我-程序以退出代码结束:0。也许没有时间在应用程序运行完成之前完成请求?
获取正确的数据并进行解析后,您应该自己调用完成功能
Alamofire.request(request)
.validate()
.responseJSON { (response) in
print(response)
completion(response["Key"]) // assume response["Key"] = [String]
}
尝试这种方式...因为您体内接收的数据很可能是json数据,所以返回Any
static func getRepolist(request: URLRequest?,
completion: ([Any]) -> ()) {
guard let request = request else { return }
Alamofire.request(request)
.validate()
.responseJSON { (response) in
case.success( _):
print(response.result.value)
let body:Any = response.result.value
completion(body)
case.failure( _):
let errData = response.data
print(String(data: errData!, encoding: String.Encoding.utf8) ?? "NO ERROR DATA")
}
}
问题实际上是,我使用了命令行工具。 所以程序在我获取数据之前终止。 通过添加以下内容轻松解决:
RunLoop.main.run(until: Date(timeIntervalSinceNow: 15))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.