我使用自定义NSURLProtocol
,以便能够从webView
中加载的表单中保存用户名和密码,并自动将用户登录。
我的问题是我可以获取数据,但我无法完成登录用户的操作,因为网页使用一些JS来监听响应并完成表单操作。
有办法吗?
这是我目前的CustomURLProtocol
课程:
class CustomURLProtocol: NSURLProtocol {
var connection: NSURLConnection!
override class func canInitWithRequest(request: NSURLRequest) -> Bool {
if NSURLProtocol.propertyForKey("customProtocolKey", inRequest: request) != nil {
return false
}
return true
}
override class func canonicalRequestForRequest(request: NSURLRequest) -> NSURLRequest {
return request
}
override func startLoading() {
let newRequest = request.mutableCopy() as! NSMutableURLRequest
NSURLProtocol.setProperty(true, forKey: "customProtocolKey", inRequest: newRequest)
// Look for user credentials
if request.URL?.description == "https://www.website.com/Account/Login" {
if let data = request.HTTPBody {
let dataString: String = NSString(data: data, encoding: NSASCIIStringEncoding) as! String
// Code for reading user credentials goes here
}
}
connection = NSURLConnection(request: newRequest, delegate: self)
}
override func stopLoading() {
if connection != nil {
connection.cancel()
}
connection = nil
}
func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
client!.URLProtocol(self, didReceiveResponse: response, cacheStoragePolicy: .NotAllowed)
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
client!.URLProtocol(self, didLoadData: data)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
client!.URLProtocolDidFinishLoading(self)
}
func connection(connection: NSURLConnection!, didFailWithError error: NSError!) {
client!.URLProtocol(self, didFailWithError: error)
}
}
我的逻辑中是否有我遗漏或错误的东西?
提前致谢
答案 0 :(得分:0)
因此,如果我理解正确,您只是为了保留凭据而拦截通话,以便您以后可以自动登录用户?如果您只关心登录请求,可以将网址检查移至canInitWithRequest,但这是一个副问题。
正确使用自定义NSURLProtocol不应影响响应,因此网页应该正常运行。我注意到你正在使用不推荐使用的NSURLConnection,所以你可能想看看使用NSURLSession,但这又是一个副作用。
您是否已逐步查看代码以查看其失败的位置?您的连接委托方法是否被调用?是" webViewDidFinishLoad"在网络视图上被调用?
或者您不是在谈论初始表单提交,而是在您尝试使用存储的凭据登录用户时的后续表单?