gpt4 book ai didi

swift - 基本身份验证 swift 4

转载 作者:行者123 更新时间:2023-11-30 11:37:22 24 4
gpt4 key购买 nike

我创建了一个使用 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;
}

我的代码有什么问题?

最佳答案

不使用下一步操作:

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

将其更改为:

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

查看此thread .

关于swift - 基本身份验证 swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49601374/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com