【问题标题】:What should I do on logging out when Alamofire request is authenticated?当 Alamofire 请求通过身份验证时,我应该如何注销?
【发布时间】:2016-04-18 09:11:17
【问题描述】:

我正在使用Alamofire 请求所有网络呼叫。最初,当我登录时,我使用一些 USERNAME 和 PASSWORD 验证请求。假设 USERNAME 是 JOHN,PASSWORD 是 1234。

假设我立即注销并使用其他凭据登录,例如 USERNAME 是 PETER,PASSWORD 是 4321。应用程序仅使用旧凭据 JOHN 和 1234 再次登录。根本没有应用新值。

退出时,退出时我应该怎么做才能删除之前的会话?

添加了sn-p

func login(userName: String!, password:String!, completion: (error: NSError?) -> Void) {
        print(userName)  // Prints PETER for second attempt
        Alamofire.request(
            .GET,
            Management.LOGIN_URL)
            .authenticate(user: userName , password: password)
            .responseJSON { response in
                // But gives JOHN's data for second attempt
                switch response.result {
                case .Success(let JSON):
                    print(JSON)
                    self.setCookies(response)
                    self.setUserData(JSON as! NSDictionary)
                    completion(error: error)  
                    }

                case .Failure(let error):
                    completion(error: error)
                }
        }
    }

func logout() {
        Alamofire.Manager.sharedInstance.session.resetWithCompletionHandler { () -> Void in
            print("Resetted")
        }
    }

private func setCookies(response: Alamofire.Response<AnyObject, NSError>) {
        if let
            headerFields = response.response?.allHeaderFields as? [String: String],
            URL = response.request?.URL
        {
            let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(headerFields, forURL: URL)
            Alamofire.Manager.sharedInstance.session.configuration.HTTPCookieStorage?.setCookies(cookies, forURL: response.response!.URL!, mainDocumentURL: nil)
        }
    }

【问题讨论】:

  • 你能展示你尝试过的代码吗
  • 你在哪里调用了这个login方法
  • 在我的 LoginViewController 中。我这里添加的sn-p是我的APIManager
  • 你能证明那个方法Alamofire.Manager.sharedInstance.login
  • 这是 LoginViewController 中的一个按钮动作。我将文本字段值作为用户名和密码传递

标签: ios iphone authentication alamofire


【解决方案1】:

授权标头中的身份验证帮助了我。

let user = "user"
let password = "password"

let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
let base64Credentials = credentialData.base64EncodedStringWithOptions([])

let headers = ["Authorization": "Basic \(base64Credentials)"]

Alamofire.request(.GET, "https://httpbin.org/basic-auth/user/password", headers: headers)
         .responseJSON { response in
             debugPrint(response)
         }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    • 2023-03-15
    • 1970-01-01
    • 2015-07-25
    相关资源
    最近更新 更多