4

Using Alamofire 4.0 and Swift 3.0 this works:

Alamofire.request("http://content.uplynk.com/player/assetinfo/ab19f0dc98dc4b7dbfcf88fa223a6c3b.json", method: .get).responseJSON {
(response) -> Void in
print("Success: \(response.result)")
}

Success: SUCCESS

However when I try to use the Sessionmanager so I can include a timeoutInterval, my requests always fail

let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 15
let alamofireManager = Alamofire.SessionManager(configuration: configuration)   
alamofireManager.request("http://content.uplynk.com/player/assetinfo/ab19f0dc98dc4b7dbfcf88fa223a6c3b.json").validate().responseJSON { 
    response in
    print("Success: \(response.result)")
    print("Response String: \(response.result.value)")
}

Success: FAILURE

Would be grateful if someone could help point me in the right direction here.

help-info.de
  • 6,695
  • 16
  • 39
  • 41
Mike O
  • 81
  • 1
  • 4

1 Answers1

15

By printing response.result.error I got:

Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLKey=http://content.uplynk.com/player/assetinfo/ab19f0dc98dc4b7dbfcf88fa223a6c3b.json, NSLocalizedDescription=cancelled, NSErrorFailingURLStringKey=http://content.uplynk.com/player/assetinfo/ab19f0dc98dc4b7dbfcf88fa223a6c3b.json}

Which lead me to this reference:

You need to make sure that the manager is retained. The difference here is that the initialized manager is not owned, and is deallocated shortly after it goes out of scope. As a result, any pending tasks are cancelled.

Solution:

One way to solve the issue your having is by declaring the custom session manager outside of the class declaration as a global variable like so...

let sessionManager: SessionManager = {
  let configuration = URLSessionConfiguration.default
  configuration.timeoutIntervalForRequest = 15

  return SessionManager(configuration: configuration)
}()

Now, within your class you can make the request.

class ViewController: UIViewController {

  let url = "http://content.uplynk.com/player/assetinfo/ab19f0dc98dc4b7dbfcf88fa223a6c3b.json"

  override func viewDidLoad() {
    super.viewDidLoad()

    sessionManager.request(url).validate().responseJSON { response in
      switch response.result {
        case .success:
          print(response.result.value as! NSDictionary)
          break

        case .failure:
          print(response.result.error!)
          break
      }
    }
  }

}

Which shall give you what you're looking for. Hope that helps!

dispatchswift
  • 1,046
  • 9
  • 21
  • 1
    very very helpful and this absolutely solves my issue. thanks very much for taking the time to reply with such a thorough answer and example! – Mike O Nov 25 '16 at 18:24