无法使用Alamofire获取数据?

编程入门 行业动态 更新时间:2024-10-15 08:24:22
本文介绍了无法使用Alamofire获取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图从我的Django后端获取iOS应用程序中的数据。在邮递员中,如果我对以下 URL执行GET请求,请

解决方案

你在这里有一个错字:

let params = [Authorization:Bearer+ access_token]

您在持票人后缺少空格。

I am trying to fetch data in my iOS app from my Django backend. In postman if I perform a GET request on the following URL 127.0.0.1:8000/api/places/categories with the params being Key:"Authorization" Value: "Bearer access_token".I get a JSON response.

Inside my app I am doing something like this with the help of Alamofire:

let access_token = "123" let headers = ["Authorization": "Bearer" + access_token] Alamofire.request(self.categoriesUrl, method: .get, parameters:nil,encoding: JSONEncoding.default,headers: headers).response { response in print("Request: \(response.request)") print("Response: \(response.response)") print("Error: \(response.error)") if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) { print("Data: \(utf8Text)") } }

I get an error saying Authorization Credentials were not provided. I understand this and it asks me to pass in the parameters but the parameters just need a token. So I do something like this:

let access_token = "123" let params = ["Authorization": "Bearer" + access_token] Alamofire.request(self.categoriesUrl, method: .get, parameters:params,encoding: JSONEncoding.default,headers: nil).response { response in print("Request: \(response.request)") print("Response: \(response.response)") print("Error: \(response.error)") if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) { print("Data: \(utf8Text)") } }

It waits for a while but fails to fetch the data with the following error:

Response: nil Error: Optional(Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x61800004b0d0 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=127.0.0.1:8000/api/places/categories/, NSErrorFailingURLKey=127.0.0.1:8000/api/places/categories/, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.}) Data:

EDIT1:

解决方案

You have a typo here :

let params = ["Authorization": "Bearer" + access_token]

You're missing a space after Bearer.

更多推荐

无法使用Alamofire获取数据?

本文发布于:2023-11-26 02:19:15,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   Alamofire

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!