2017-05-07 52 views
0

我有一個受保護的API,並且我得到了它的用戶名和密碼。當我使用郵遞員時,我選擇「基本身份驗證」類型,並在身體中擁有諸如用戶登錄信息等參數。它工作得很好。Alamofire的基本驗證標題

enter image description here

但是我試圖做Alamofire同樣的事情,但我不能得到正確的JSON回報。這是我做的:

// user auth 
    let param = ["mobile":"3", "password":"100200"] 
    let urlStr = "http://MyApi.com/api/login" 
    let url = URL(string: urlStr) 

    // api auth 
    let user = "apiUserName" 
    let password = "ApiAuthPassword" 


    var headers: HTTPHeaders = ["mobile":"001", 
           "password":"1111"] 

    if let authorizationHeader = Request.authorizationHeader(user: user, password: password) { 
     headers[authorizationHeader.key] = authorizationHeader.value 
    } 

    Alamofire.request(url!, headers: headers) 
     .responseJSON { response in 

      print(response.result.value) 
      if let value: AnyObject = response.result.value as AnyObject? { 
       //Handle the results as JSON 
       print(value) 
       let usertoken = JSON(value) 

       print(usertoken) 
      } 



    } 

這返回nil。有人可以幫助我如何用Alamofire做郵遞員方法。謝謝!

回答

0
let user = "your username" 

let password = "your password" 

let credentialData = "\(user):\(password)".data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))! 

let base64Credentials = credentialData.base64EncodedString() 


    let headers = [ 
      "Authorization": "Basic \(base64Credentials)", 
      "Accept": "application/json", 
      "Content-Type": "application/json" ] 

//put slash before \ (base64Credentials) 

    Alamofire.request("place your url", method: .get, parameters: nil,encoding: URLEncoding.default, headers: headers) .responseJSON { response in 
     switch response.result { 
      case .success(_): 
       //your success code 
      }  
      case .failure(_): 
       //your failure code 
      } 
    }