swift 线程1:信号SIGABRT alamofire

up9lanfz  于 2024-01-05  发布在  Swift
关注(0)|答案(1)|浏览(164)

我对Swift 3很陌生,我必须在我的API上做一个GET请求。我使用的是Alamofire,它使用异步函数。
我在我的Android应用程序上做了完全相同的事情,GET返回JSON数据
这是我在Swift中的代码:

  1. func getValueJSON() -> JSON {
  2. var res = JSON({})
  3. let myGroup = DispatchGroup()
  4. myGroup.enter()
  5. Alamofire.request(url_).responseJSON { response in
  6. res = response.result.value as! JSON
  7. print("first result", res)
  8. myGroup.leave()
  9. }
  10. myGroup.notify(queue: .main) {
  11. print("Finished all requests.", res)
  12. }
  13. print("second result", res)
  14. return res
  15. }

字符串
但是我对“res = response.result.value”这一行有问题,它给了我错误:
线程1:信号SIGABRT
我真的不明白问题出在哪里,做一个“同步”功能很难,也许我做错了。
我的目标是将请求的结果存储在我返回的变量中。有人能帮忙吗?

ee7vknir

ee7vknir1#

我建议你将Alamofire和SwiftyJSON一起使用,因为这样你就可以更容易地解析JSON。
这里有一个经典的例子:

  1. Alamofire.request("http://example.net", method: .get).responseJSON { response in
  2. switch response.result {
  3. case .success(let value):
  4. let json = JSON(value)
  5. print("JSON: \(json)")
  6. case .failure(let error):
  7. print(error)
  8. }
  9. }

字符串
如果需要传递parametersheaders,只需将其添加到request方法中。

  1. let headers: HTTPHeaders = [
  2. "Content-Type:": "application/json"
  3. ]
  4. let parameters: [String: Any] = [
  5. "key": "value"
  6. ]


所以你的请求会是这样的(这是POST请求):

  1. Alamofire.request("http://example.net", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
  2. switch response.result {
  3. case .success(let value):
  4. print(value)
  5. case .failure(let error):
  6. print(error)
  7. }
  8. }


我还没有测试过,但它应该工作.另外,你需要设置allow arbitary loadyesinfo.plist中的App Transport Security Settings)如果你想允许通过HTTP协议的请求.
这是不推荐的,但它对开发很好。

展开查看全部

相关问题