2017-08-16 182 views
0

我想从我的Django后端获取iOS应用程序中的数据。在postman中,如果我对以下URL http://127.0.0.1:8000/api/places/categories执行GET请求,其参数是Key:"Authorization" Value: "Bearer access_token".,我得到一个JSON响应。无法使用Alamofire获取数据?

里面我的应用我做这样的事情与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)") 
      } 
     } 

我得到一个错误说授权证书没有提供。我明白这一点,它要求我传递参数,但参数只需要一个令牌。所以,我做这样的事情:

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)") 
      } 
     } 

它等待一段时间,但失败并出现以下错误获取数据:

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=http://127.0.0.1:8000/api/places/categories/, NSErrorFailingURLKey=http://127.0.0.1:8000/api/places/categories/, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.}) 
Data: 

EDIT1: POST MAN SCREENSHOT

+0

我猜这个错误主要是由于没有连接到互联网,请检查您的互联网连接, – 3stud1ant3

+0

这不是因为互联网。邮差工作正常,并请求也 – indexOutOfBounds

+0

你确定头是零,你可以显示帖子人的请求,可能[“授权”:“承载”+ access_token]是标题,而不是params – 3stud1ant3

回答

0

这是非常很容易修复,我猜你正在使用iOS10或更高版本的操作系统。因此,不要拨打http,只需拨打https即表示在iOS10及更高版本中API呼叫协议已更改为httphttps

+0

我应该在哪里做到这一点?你的意思是在我请求的网址中? – indexOutOfBounds

+0

是的,而不是http://127.0.0.1:8000/api/places/categories,调用https://127.0.0.1:8000/api/places/categories –

+0

它不这样工作。 – indexOutOfBounds

0

您在这里有一个错字:

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

你缺少承载后的空间。

+0

无论我做什么,我的参数不能为零?这是为什么?你可以看到我发布的邮差截图。那么我通过哪些参数? – indexOutOfBounds