我正在尝试使用URLSession进行摘要身份验证。
class AuthenticateHandler: NSObject, URLSessionTaskDelegate,URLSessionDelegate {
func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let credentials = URLCredential(user: UserDefaults.standard.string(forKey: "userName") ?? "admin", password: UserDefaults.standard.string(forKey: "password") ?? "admin", persistence: URLCredential.Persistence.forSession)
completionHandler(URLSession.AuthChallengeDisposition.useCredential,credentials)
}
}
该呼叫在cameramanager中:
class CameraManager: NSObject, NetworkProtocols {
let handler = AuthenticateHandler()
var urlSession: URLSession?
override init() {
super.init()
let config = URLSessionConfiguration.default
config.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData
config.urlCache = nil
self.urlSession = URLSession(configuration: config, delegate: handler, delegateQueue: OperationQueue.main)
}
func imageCall(url: String , success: @escaping (UIImage) -> Void, failure: @escaping () -> Void) {
let imageThumbnailTask = urlSession?.dataTask(with: URL(string:url)!) { data, res, err in
if err != nil {
print("error from dataResponse:\(err?.localizedDescription ?? "Response Error")")
failure()
}
if let imageData = data, let image = UIImage(data: imageData) {
success(image)
}
}
imageThumbnailTask?.resume()
}
}
实现的类如下:
self.network.imageCall(url: self.isShowingThermal ? self.thermalUrl : self.visualUrl, success: { [weak self] (image) in
self?.indicaotrTimer?.invalidate()
self?.imageLoaderIndicator.stopAnimating()
DispatchQueue.main.async{
self?.seconds = 1
self?.backGroundImageView.image = image
}
if self?.isInVC ?? false {
self?.imageBackgroundCall()
}
}) {
if self.isInVC {
self.imageBackgroundCall()
}
}
一段时间后,我得到一个奇怪的行为,摘要停止使用状态码401,标题(未收到错误-响应401中显示了imageThumbnailTask)。 调试它时,由于某种原因它不会在AuthenticateHandler类中停止。 响应如下所示:
有什么想法吗?
result: Optional(<NSHTTPURLResponse: 0x1d4237940> { URL: http://192.168.42.1/images/snapshots/DLTVimage.jpeg } { Status Code: 401, Headers {
Connection = (
"keep-alive"
);
"Content-Length" = (
195
);
"Content-Type" = (
"text/html"
);
Date = (
"Mon, 07 Jan 2019 00:13:17 GMT"
);
} })
p.s
也用Alamofire尝试过:
class CameraManager: NSObject, NetworkProtocols {
var sessionMananager: Alamofire.SessionManager?
override init() {
super.init()
initAlamoSession()
}
func initAlamoSession() {
self.credential = URLCredential(user: UserDefaults.standard.string(forKey: "userName") ?? "admin", password: UserDefaults.standard.string(forKey: "password") ?? "admin", persistence: .forSession)
let config = URLSessionConfiguration.default
config.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData
config.urlCache = nil
self.sessionMananager = Alamofire.SessionManager(configuration: config)
}
func imageCall(url: String , success: @escaping (UIImage) -> Void, failure: @escaping () -> Void) {
print("imageCall")
sessionMananager?.request(url)
.authenticate(usingCredential: self.credential!)
.responseJSON { response in
print("Result: \(String(describing: response.response?.statusCode))")
if let data = response.data {
if let image = UIImage(data: data) {
print("imageCal success")
success(image)
} else {
print("imageCal failure")
failure()
}
} else {
failure()
}
}
}
}