Set token in WKWebView swiftui

I am sending the authorization token to the WKWebView. However, after the redirect, the server does not receive the token. How can I send a token so that it does not disappear during a redirect.

I'm sorry, can you explain in a bit more detail what you're doing?

What exactly are you sending to WKWebView, and how? Are you using the WebURL library/type?

I am not using a library.
I need to be authenticated in social media. network "VKontakte".
To do this, I need to send a GET request to my server along with an access token.

I am sending a request.
An authorization window opens on the webview.
On the server side, you can see that the token has been received.

However, after entering the passwords and clicking on the "send" buttons, the web page redirects and in this request the token does not arrive at the server.

My code

struct WebView: UIViewRepresentable{
    @Binding var title: String
    @Binding var url: String
    @State var state: WebViewSwitchEnum = .ESIA
    @State var cleanAllCookes: Bool
    
    
    let userDefaults = UserDefaults.standard
    let view = WKWebView()
    
    var loadStatusChanged: ((Bool, Error?) -> Void)? = nil

    func makeCoordinator() -> WebView.Coordinator {
        Coordinator(self)
    }

    func makeUIView(context: Context) -> WKWebView {
 
        var request = URLRequest(url: URL(string: url)!)
        if cleanAllCookes == true {
            view.cleanAllCookies()
        }
        view.navigationDelegate = context.coordinator
        
        switch(state){
        case .ESIA: do {
            
        }
        case .SOCIAL_NETWORK: do {
            request.allHTTPHeaderFields = [
                "Authorization": "Bearer \(userDefaults.string(forKey: "ACCESS_TOKEN")!)",
                "Content-Type": "application/json"
            ]
        }
        }
        
        request.httpMethod = HTTPMethod.get.rawValue
        print(request)
        view.load(request)
        return view
    }
    
    //Обновляет страницу после каждой переадресации
    func updateUIView(_ uiView: WKWebView, context: Context) {
        
    }

    //Для отслежения состояние загрузки "Загружается" и "Конец загрузки"
    func onLoadStatusChanged(perform: ((Bool, Error?) -> Void)?) -> some View {
        var copy = self
        copy.loadStatusChanged = perform
        return copy
    }

    //Получение JavaScrit текста из WKWebView
    func getJSON (completion: @escaping(String) -> ()){
        switch(state){
        case .ESIA: do {
            view.evaluateJavaScript("document.body.textContent", completionHandler: { (res, error) in
                if let fingerprint = res {
                    completion(fingerprint as! String)
                }
            })
        }
        case .SOCIAL_NETWORK: break;
        }
    }

    class Coordinator: NSObject, WKNavigationDelegate {
        let parent: WebView

        init(_ parent: WebView) {
            self.parent = parent
        }

        func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
            parent.loadStatusChanged?(true, nil)
        }

        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
            parent.title = webView.title ?? ""
            parent.loadStatusChanged?(false, nil)
        }
  
        func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse) async -> WKNavigationResponsePolicy {
            
            return .allow
        }

        func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
            parent.loadStatusChanged?(false, error)
        }
 
    }
}

OK, well this category is for the WebURL library. I can understand why you posted it here, but the correct place would be the "Using Swift" category, or even the Apple developer forums (since this seems to be more about Apple frameworks than the Swift language).

If I knew why this wasn't working, I'd help anyway, but I don't. Maybe somebody else does. I've moved your topic in to a more appropriate category so they're more likely to see it.

1 Like