3

at all, I created a function that sends a "GET" request, to a amazon aws server, and gets a response in JSON, and then these data are placed in a table. When I first call this data, everything works perfectly, but when I get back to the home screen and open the view again with the table, the same function fails, returning an incorrect header error, even though it worked for the first time, I attach the code:

Function:

func getData(url:String, complete: @escaping ([Int:Any]) -> Void) {
    var array: [Int:Any] = [:]
    let headers = [
        "authorization": "Bearer codeBearer",
        "cache-control": "no-cache"
    ]
    print(headers)
    print(url)
    let request = NSMutableURLRequest(url: NSURL(string: url)! as URL, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 10.0)
    request.httpMethod = "GET"
    request.allHTTPHeaderFields = headers
    let session = URLSession.shared
    let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
        if (error != nil) {
            print(error!) // errore
        } else {
            let input = String(data: data!, encoding: .utf8)?.data(using: .utf8) // json
            let json = try! JSON(data: input!)
            print(json)
            for (_,subJson):(String, JSON) in json {
                let num = subJson["index"].int
                if( num != nil ){
                    array[num!] = subJson
                }
            }
            session.invalidateAndCancel()
            complete(array)
        }
    })
    dataTask.resume()
}

View:

@IBOutlet weak var table: UITableView!

func reload(){
    DispatchQueue.main.async{
        self.table.reloadData()
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    if( idCell == "cell" ){
        fun.getData(url: fun.request("/v1/media", test: true), complete: { success in
            self.array = success
            self.reload()
        })
    }else{
        fun.getData(url: fun.request("/v1/banner", test: true), complete: { success in
            self.array = success
            self.reload()
        })
    }
}

Error:

    {
  "message" : "'codeBearer' not a valid key=value pair (missing equal-sign) in Authorization header: 'Bearer codeBearer'."
}

If I try to send the request through the curl, it works every time, while here only works the first time I perform the function, but if I close and reopen the application it works again for the first time, tips on how to fix it?

peppinoibra
  • 139
  • 1
  • 10

2 Answers2

0

To cleanup your session invoke below.

session.invalidateAndCancel()
Hussain Shabbir
  • 14,801
  • 5
  • 40
  • 56
0

I Know this answer is very late, but i faced this same issue when consuming SOAP web service.

You should use ephemeral session on a SOAP service call when you are invoking it like a REST service call.

Example Code

let session = URLSession(configuration: .ephemeral)

Here is the documentation form apple about various types of URL Sessions

  1. A default session behaves much like the shared session, but allows more configuration, and allows you to obtain data incrementally with a delegate.

  2. Ephemeral sessions are similar to shared sessions, but don’t write caches, cookies, or credentials to disk.

  3. Background sessions let you perform uploads and downloads of content in the background while your app isn't running.

Christlin Panneer
  • 1,599
  • 2
  • 19
  • 31