基本认证swift 4

时间:2018-04-01 18:36:49

标签: swift http authentication

我创建了一个使用REST API的iOS应用程序。我创建了一个REST API管理器类,其中包含以下代码:

import UIKit

class APIManager: NSObject, {
    let baseURL = "http://example.com/api/"
    static let sharedInstance = APIManager()

    let credential = URLCredential(user: "user", password: "password", persistence: URLCredential.Persistence.forSession)
    let protectionSpace = URLProtectionSpace.init(host: "example.com", port: 80, protocol: "http", realm: "Restricted", authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
    let config = URLSessionConfiguration.default
    func request(verb: String, action: String, data: [String:String]?) -> URLRequest {
        var urlString : String = baseURL + action
        var dataString = ""
        var formData = false
        if let data = data {
            for (key, value) in data {
                if (dataString != "") {
                    dataString += "&"
                }
                dataString += key + "="
                dataString += value.base64Encoded()!
            }
            if (verb == "get") {
                urlString += "?" + dataString
                formData = false
                } else {
                formData = true
            }
        }
        let url = URL(string : urlString)!
        var request = URLRequest(url: url)
        request.httpMethod = verb
        if formData {
            request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
            request.httpBody = dataString.data(using:.utf8)
        }
        URLCredentialStorage.shared.setDefaultCredential(credential, for: protectionSpace)

        return request
        }
    func get(action: String, data: [String:String]?, onSuccess: @escaping(Int, String) -> Void, onFailure: @escaping(Error) -> Void) {
    let request = self.request(verb: "get", action: action, data: data)
        let session =   URLSession(configuration: config)
        let task = session.dataTask(with: request as URLRequest, completionHandler: {dataBody, response, error -> Void in
            if (error != nil) {
                onFailure(error!)
            } else {
                let dataString = String(data:dataBody!, encoding : String.Encoding.utf8) as String?
                let responseCode = (response as! HTTPURLResponse?)!.statusCode
                onSuccess(responseCode, dataString!)
            }
        })
        task.resume()
    }

当我尝试发送请求时,我收到以下错误:

    CredStore - performQuery - Error copying matching creds.  Error=-25300, query={
    atyp = http;
    class = inet;
    "m_Limit" = "m_LimitAll";
    ptcl = http;
    "r_Attributes" = 1;
    sdmn = "CnD REST API";
    srvr = "cookndinner.atwebpages.com";
    sync = syna;
  }

我的代码有什么问题?

1 个答案:

答案 0 :(得分:0)

不要使用下一步操作:

URLCredentialStorage.shared.setDefaultCredential(credential, for: protectionSpace)

将其更改为:

let userCredential = URLCredential(user: user, 
                               password: password, 
                               persistence: .permanent)
URLCredentialStorage.shared.setDefaultCredential(userCredential, for: protectionSpace)

请参阅此thread