2017-08-16 180 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