【发布时间】:2016-04-18 06:54:34
【问题描述】:
我正在使用自定义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)
}
}
我的逻辑有什么遗漏或错误吗?
提前致谢
【问题讨论】:
标签: ios iphone swift uiwebview nsurlprotocol