Trouble with Instagram API Authorization Code Exchange in Swift using URLSession

41 Views Asked by At

I am currently facing issues with exchanging an Instagram authorization code for an access token in my Swift application using URLSession. When I make the request using Postman, I receive the expected response; however, when I implement the same logic in Swift, the response is a large, unmanageable string.

Here's a snippet of my Swift code:

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            print("Error: \(error)")
            return
        }
    
        if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode != 200 {
            print("HTTP Status Code: \(httpResponse.statusCode)")
            print("Response: \(response)")
            // Additional error handling if needed
        }
    
        do {
            let decoder = JSONDecoder()
            let response = try decoder.decode(AccessTokenResponse.self, from: data)
            print("Access Token: \(response.accessToken)")
            // Handle the response as needed
        } catch {
            print("Error decoding JSON: \(error)")
        }
    }
task.resume()


func checkRequestForCallbackURL(request : URLRequest) -> Bool {
        let requestURLString = (request.url?.absoluteString)! as String
        if requestURLString.starts(with: "\(SocialAccountCredentials.instagramCallBackUrl)?code=") {
            if let range = requestURLString.range(of: "\(SocialAccountCredentials.instagramCallBackUrl)?code=") {
                print("request string = \(requestURLString)")
                let newCode = String(requestURLString[range.upperBound...].dropLast(2))
                print("newCode = \(newCode)")
                handleAuth(authToken: newCode)
                return false
                
            }
        }
        return true
    }


let authURL = URL(string: "https://api.instagram.com/oauth/authorize?client_id=\(SocialAccountCredentials.instagramClientId)&redirect_uri=\(SocialAccountCredentials.instagramCallBackUrl)&scope=user_profile,user_media&response_type=code")
        print("authURL is \(authURL)")
        let urlRequest = URLRequest(url: authURL!)
        wbView?.load(urlRequest)
0

There are 0 best solutions below