1

I am making API calls in Swift using URLSession and I want to add option in my request whether to allow redirects of a request (followRedirect) but I don't know how to accomplish it.. I think there is a way in Alamofire but I can not use external library for this task...

i.e. In NodeJS you can do

var 'https' = require('follow-redirects').'https'; 
//and add this in field in options of https.request allowing max 21 redirects
   'maxRedirects': 21

If someone know how to do it.. Please let me know..

This is my snippet, let me know of any suggested changes.

import Foundation

var sema = DispatchSemaphore (value: 0)

var request = URLRequest(url: URL(string: "https://mockbin.org/request")!, timeoutInterval: 2000)
request.httpMethod = "GET"

let task = URLSession.shared.dataTask(with: request) { data, response, error in 
    guard let data = data else {
        print(String(describing: error))
        return
    }
    print(String(data: data, encoding: .utf8)!)
    sema.signal()
}

task.resume()
sema.wait()
ShinKinn
  • 66
  • 1
  • 8
  • Possible duplicate of [NSURLSession 3xx redirects and completion handlers](https://stackoverflow.com/questions/37620874/nsurlsession-3xx-redirects-and-completion-handlers) – trojanfoe Feb 08 '19 at 07:23
  • @trojanfoe I am looking for an option which has shred instance of URLSession... – ShinKinn Feb 08 '19 at 07:52
  • The linked answer takes you to the docs for `URLSessionTaskdelegate`, which has a method (urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)) that allows a delegate to be informed of redirects and prevent or allow following (https://developer.apple.com/documentation/foundation/urlsessiontaskdelegate/1411626-urlsession) – Chris Feb 08 '19 at 09:16

0 Answers0