快速将所有HTTPHeaderFields添加到URLRequest

时间:2018-07-08 18:37:06

标签: swift xcode

我正在尝试将承载令牌添加到URLrequest中,但不幸的是,该请求为nil,我不知道自己是否以正确的方式进行操作,但目前无法正常工作。 我的意图是添加用户令牌或匿名令牌,这取决于两点:

  • 如果我已将用户令牌存储在钥匙串(SessionProvider)中,并且与此用户令牌相关的刷新令牌未过期,则将用户令牌添加到请求中
  • 如果我已将用户令牌存储在钥匙串(SessionProvider)中,但与此用户令牌相关的刷新令牌已过期,则将匿名令牌添加到请求中
  • 如果我尚未将用户令牌存储在钥匙串(SessionProvider)中,则将匿名令牌添加到请求中

这些是我想包括的3种可能性,用于填写URLrequest,但是当我

  

print(“ request(request.allHTTPHeaderFields)”)

控制台中的结果为

  

request可选([:])

我该怎么做才能获得理想的结果?

 public static var fake: Resource<[User]> = Resource(request: { (url) -> URLRequest in
        var components = URLComponents(url: url, resolvingAgainstBaseURL: true)!
        components.path = "/dev/fake-users"
        var request = URLRequest(url: components.url!)
        request.httpMethod = "GET"

        if let token = SessionProvider().getUserToken(){
            SessionController().refreshToken(refreshToken: (SessionProvider().getUserToken()?.refreshToken)!, completion: { (error) in
                if let error = error{
                    if let anonymousToken = SessionProvider().getAnonymousToken(){
                        request.setValue("Bearer \(anonymousToken)", forHTTPHeaderField: "Authorization")
                    }
                }else{
                   request.setValue("Bearer \(token.accessToken)", forHTTPHeaderField: "Authorization")
                }
            })
        }
        else if let anonymousToken = SessionProvider().getAnonymousToken(){
            request.setValue("Bearer \(anonymousToken)", forHTTPHeaderField: "Authorization")
        }

        print("request \(request.allHTTPHeaderFields)")

        return request

    }) { (data) -> [User] in
        let unboxer = Unboxer(dictionary: data as! UnboxableDictionary)
        return try unboxer.unbox(key: "hits")
    }

现在刷新令牌功能

  
 public static func refreshToken(refreshToken: String) -> Resource<String> {
        return Resource(request: { (url) -> URLRequest in

            var components = URLComponents(url: url, resolvingAgainstBaseURL: true)!
                components.path = "/v1/oauth/login"

            var request = URLRequest(url: components.url!)
                request.httpMethod = "POST"
                request.setValue("Basic \(Keys.basic)", forHTTPHeaderField: "Authorization")
                request.setValue(SessionProvider().getInstanceToken(), forHTTPHeaderField: "x-bok-instance")

            var dictionary: [String: Any] = [:]
                dictionary["refreshToken"] = refreshToken
                dictionary["grantType"] = "refresh_token"

            request.httpBody = try? JSONSerialization.data(withJSONObject: dictionary, options: [])
            return request
        }, dataParser: { data -> String in
            let unboxer = try Unboxer(data: data)
            return try Unboxer(data: data).unbox(key: "accessToken")
        })
    } 

0 个答案:

没有答案