使用swift 3中的urlsession在http标头中发送持有者令牌的问题

时间:2017-06-28 10:45:08

标签: ios json swift3 http-headers urlsession

我正在使用urlsession在标头中发送持有人令牌,但我总是将结果视为未经授权。我见过服务器日志。我正在那里,但没有标题。

    let key = UserDefaults.standard.object(forKey: "loginKey") as! String
        print(key)
        let url = NSURL(string: baseurl+"***")

        let request = NSMutableURLRequest(url: url! as URL)

        request.httpMethod = "GET"

        request.addValue("Bearer " + key, forHTTPHeaderField: "Authorization")
        let task = URLSession.shared.dataTask(with: request as URLRequest) 
{(data,response,error) -> Void in

        if error != nil
        {
          print(error?.localizedDescription as Any)
                        return
        }

       do 
       {
          let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary

           print(json)
        }
      catch let error as NSError 
      {
         print(error.localizedDescription)
      }
    }
    task.resume()

我也试过request.setValue("Bearer " + key, forHTTPHeaderField: "Authorization")

1 个答案:

答案 0 :(得分:5)

试试这个:

     var sessionConfig = URLSessionConfiguration.default
      var authValue: String? = "Bearer \(key)"
     sessionConfig.httpAdditionalHeaders = ["Authorization": authValue ?? <#default value#>]
     var session = URLSession(configuration: sessionConfig, delegate: self as? URLSessionDelegate, delegateQueue: nil)