Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
iOS如何向每个UIWebView请求添加cookie?_Ios_Swift_Cookies_Uiwebview - Fatal编程技术网

iOS如何向每个UIWebView请求添加cookie?

iOS如何向每个UIWebView请求添加cookie?,ios,swift,cookies,uiwebview,Ios,Swift,Cookies,Uiwebview,我需要在UIWebView中使用Angular打开URL,并且我需要在每个UIWebView请求中发送cookie 我想做的是: 我试图检查请求是否包含cookie。如果它执行请求,则使用cookie创建相同的请求并执行它。为了替换请求,我使用了UIWebViewDelegate的方法func-webView(\uwebview:UIWebView,shouldStartLoadWith-request:URLRequest,navigationType:UIWebViewNavigationT

我需要在
UIWebView
中使用Angular打开URL,并且我需要在每个
UIWebView
请求中发送cookie

我想做的是:

我试图检查请求是否包含cookie。如果它执行请求,则使用cookie创建相同的请求并执行它。为了替换请求,我使用了
UIWebViewDelegate
的方法
func-webView(\uwebview:UIWebView,shouldStartLoadWith-request:URLRequest,navigationType:UIWebViewNavigationType)->Bool
。但它的工作原理与我预期的不同,有些请求在没有cookie的情况下执行

我的代码:

final class FieldServiceViewController: UIViewController {

    private var webView = UIWebView()
    private var sessionID = String()

    override func viewDidLoad() {
        super.viewDidLoad()

        _ = JSONAPI.getSessionID().subscribe(onNext: { [weak self] sessionID in
            self?.sessionID = sessionID
            self?.configureUI()
            let string = "https://someURL"
            let url = URL(string: string)
            let request = URLRequest(url: url!)
            self?.webView.loadRequest(request)
        })
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        webView.frame = view.bounds
    }

    private func configureUI() {
        webView.delegate = self
        view.addSubview(webView)
    }

    private func cookedRequest(from: URLRequest) -> URLRequest? {

        let cookiesKey = "Cookie"
        let headers = from.allHTTPHeaderFields ?? [:]
        if (headers.contains { $0.0 == cookiesKey }) {
            return nil
        }

        var request = from
        request.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData
        let cookiesToAdd = "SESSIONID=\(sessionID)"
        request.addValue(cookiesToAdd, forHTTPHeaderField: cookiesKey)
        return request
        }
    }

    extension FieldServiceViewController: UIWebViewDelegate {

    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {

        if let cooked = cookedRequest(from: request) {
            webView.loadRequest(cooked)
            return false
        }

        return true
    }
}
如何向每个UIWebView请求添加cookie


另外,我还将cookie保存在
HTTPCookieStorage
中,但看起来
UIWebView
的请求与共享存储之间根本没有任何连接。

您可以将代码更改为:

func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    if request.allHTTPHeaderFields?["SESSIONID"] == nil {
       var request: URLRequest = request
       request.allHTTPHeaderFields?["SESSIONID"] = "your_session_id"
       webView.loadRequest(request)
       return false
    }
    return true
}
更新

如我所见,解决问题的最佳方法是使用
URLProtocol
拦截您的请求。 创建下一个类:

class MyURLProtocol: URLProtocol, NSURLConnectionDelegate, NSURLConnectionDataDelegate {

    static let protocolKey = "MyURLProtocolKey"

    private var connection: NSURLConnection?

    override class func canInit(with request: URLRequest) -> Bool {
        if let isCustom = URLProtocol.property(forKey: MyURLProtocol.protocolKey, in: request) as? Bool{
            return false
        }
        return true
    }

    override class func canonicalRequest(for request: URLRequest) -> URLRequest {
        //You can add headers here
        var request = request
        print("request: \(request.url?.absoluteString ?? " ")")
        request.allHTTPHeaderFields?["SESSION_ID"] = "your_session_id"
        return request
    }

    override class func requestIsCacheEquivalent(_ a: URLRequest, to b: URLRequest) -> Bool {
        return super.requestIsCacheEquivalent(a, to: b)
    }

    override func startLoading() {
        let newRequest: NSMutableURLRequest = self.request as! NSMutableURLRequest
        URLProtocol.setProperty(true, forKey: MyURLProtocol.protocolKey, in: newRequest)
        self.connection = NSURLConnection(request: newRequest as URLRequest, delegate: self, startImmediately: true)
    }

    override func stopLoading() {
        self.connection?.cancel()
        self.connection = nil
    }

    //MARK: NSURLConnectionDataDelegate methods
    func connection(_ connection: NSURLConnection, didReceive response: URLResponse) {
        self.client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
    }

    func connection(_ connection: NSURLConnection, didReceive data: Data) {
         self.client?.urlProtocol(self, didLoad: data as Data)
    }

    func connectionDidFinishLoading(_ connection: NSURLConnection) {
        self.client?.urlProtocolDidFinishLoading(self)
    }

    func connection(_ connection: NSURLConnection, didFailWithError error: Error) {
        self.client?.urlProtocol(self, didFailWithError: error)
    }
}
现在在您的
AppDelegate

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    URLProtocol.registerClass(MyURLProtocol.self)
    return true
}
我更喜欢UIWebView,而不是UIWebView

现在,关于将会话id添加到用户发出的每个请求 项目

我不建议通过从委托方法创建新请求来添加会话id,而是建议在角度级别添加一个会话id,这将使您能够更好地控制角度项目发出的每个请求

通过匿名工厂注册拦截器

$httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  return {
   'request': function(config) {
       config.headers['SESSIONID'] = 'Your Session id here';
    },

    'response': function(response) {

    }
  };
});
现在你如何使用这个

您可以将上述代码转换为Swift字符串,当您拥有会话id并且加载了Angular项目时,您可以通过wkwebview的方法执行此操作

e、 g


谢谢你的帮助。通过创建具有特定域的cookie解决了问题:

final class FieldServiceViewController: UIViewController, DLHasHomeTitleView {

    private let fieldServiceEndPoint = Bundle.main.object(forInfoDictionaryKey: "FIELD_SERVICE_ENDPOINT") as! String

    private var webView = UIWebView()
    private var sessionID = String()

    override func viewDidLoad() {
        super.viewDidLoad()

        configureUI()

        _ = JSONAPI.getSessionID().subscribe(onNext: { [weak self] sessionID in
            guard let `self` = self else { return }

            self.sessionID = sessionID

            let urlString = "https://\(self.fieldServiceEndPoint)"
            let url = URL(string: urlString)
            let request = URLRequest(url: url!)

            let cookie = HTTPCookie(properties: [
                .name: "JSESSIONID",
                .value: sessionID,
                .path: "/",
                .domain: self.fieldServiceEndPoint])
            HTTPCookieStorage.shared.setCookie(cookie!)

            self.webView.loadRequest(request)
        })
    }

谢谢你的回答,但效果一样。有些请求执行时不需要cookies@BadCodeDeveloper你能检查一下有cookie和没有cookie的btw请求有什么区别吗?Angular执行的请求没有cookie。这就是我能看到的所有不同之处。谢谢你的回答。我试过你的解决方案,但现在我得到了白色屏幕。页面未在allwebView加载。evaluateJavaScript()返回错误:
error Domain=wkerrodomain code=4“发生JavaScript异常”UserInfo={WKJavaScriptExceptionInNumber=2,WKJavaScriptExceptionMessage=ReferenceError:找不到变量:$httpProvider,WKJavaScriptExceptionColumnNumber=15,WKJavaScriptExceptionSourceURL=about:blank,NSLocalizedDescription=JavaScript异常发生}
@BadCodeDeveloper加载角度项目后需要执行此操作
final class FieldServiceViewController: UIViewController, DLHasHomeTitleView {

    private let fieldServiceEndPoint = Bundle.main.object(forInfoDictionaryKey: "FIELD_SERVICE_ENDPOINT") as! String

    private var webView = UIWebView()
    private var sessionID = String()

    override func viewDidLoad() {
        super.viewDidLoad()

        configureUI()

        _ = JSONAPI.getSessionID().subscribe(onNext: { [weak self] sessionID in
            guard let `self` = self else { return }

            self.sessionID = sessionID

            let urlString = "https://\(self.fieldServiceEndPoint)"
            let url = URL(string: urlString)
            let request = URLRequest(url: url!)

            let cookie = HTTPCookie(properties: [
                .name: "JSESSIONID",
                .value: sessionID,
                .path: "/",
                .domain: self.fieldServiceEndPoint])
            HTTPCookieStorage.shared.setCookie(cookie!)

            self.webView.loadRequest(request)
        })
    }