Advertisement
Guest User

Untitled

a guest
Sep 20th, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.28 KB | None | 0 0
  1. static func preloadImage(sku: String) {
  2. // If the token exists AND is VALID (not expired) - Get the image.
  3.  
  4. let group = DispatchGroup()
  5. var downloadTask : RetrieveImageDownloadTask? = nil
  6.  
  7. if ImageManager.tokenExists() && ImageManager.tokenIsNotExpired(){
  8.  
  9. let imageURL = ImageManager.URLBuilder(sku: sku)
  10.  
  11. // Create the request and add the token string to the authorization header
  12. var urlRequest = try! URLRequest(url: URL(string: imageURL)!)
  13. urlRequest.setValue("Bearer (ImageManager.getTokenString()!)", forHTTPHeaderField: "Authorization")
  14. downloadTask = NetRequest.downloadImage(urlRequest: urlRequest, sku: sku)
  15. }
  16. // Else if the token exists AND is INVALID (expired) - Delete the old token, get a new one, and fetch the image
  17. else if ImageManager.tokenExists() && !ImageManager.tokenIsNotExpired(){
  18. print("Token expired... Getting new token.")
  19.  
  20.  
  21. _ = ImageManager.deleteToken()
  22. if let tokenRequest = NetRequest.newTokenRequest(url: "http://(UrlHelper.buildUrlFrom(SettingsManager.serverURL)){
  23. group.enter()
  24. tokenRequest.requestPreloadJWTToken(){
  25. let imageURL = ImageManager.URLBuilder(sku: sku)
  26.  
  27. // Create the request and add the token string to the authorization header
  28. var urlRequest = try! URLRequest(url: URL(string: imageURL)!)
  29. urlRequest.setValue("Bearer (ImageManager.getTokenString()!)", forHTTPHeaderField: "Authorization")
  30.  
  31. print("Token renewed. Fetching image...")
  32. downloadTask = NetRequest.downloadImage(urlRequest: urlRequest, sku: sku)
  33. }
  34. group.leave()
  35. }
  36. }
  37. // If the token doesn't exist, request a new one and fetch the image.
  38. else{
  39. print("Requesting new token...")
  40.  
  41. if let tokenRequest = NetRequest.newTokenRequest(url: "http://(UrlHelper.buildUrlFrom(SettingsManager.serverURL)){
  42. group.enter()
  43. tokenRequest.requestPreloadJWTToken() {
  44. print("Token aquired. Fetching image...")
  45. let imageURL = ImageManager.URLBuilder(sku: sku)
  46.  
  47. // Create the request and add the token string to the authorization header
  48. var urlRequest = try! URLRequest(url: URL(string: imageURL)!)
  49. urlRequest.setValue("Bearer (ImageManager.getTokenString()!)", forHTTPHeaderField: "Authorization")
  50.  
  51. downloadTask = NetRequest.downloadImage(urlRequest: urlRequest, sku: sku)
  52. }
  53. group.leave()
  54. }
  55. }
  56. // This should always happen
  57. group.notify(queue: DispatchQueue.main) {
  58. MainController.imageDownloadTasks.append(downloadTask!)
  59. }
  60. }
  61.  
  62. func requestPreloadJWTToken(completionHandler: @escaping () -> (/*RetrieveImageDownloadTask*/))
  63. {
  64. // Get the server name, username, and password
  65. let username = SettingsManager.username
  66. let password = SettingsManager.password
  67.  
  68. let queue = DispatchQueue(label: "Token-Request", qos: .utility, attributes: [.concurrent])
  69.  
  70. // Get download directory
  71. let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory, in: .userDomainMask)
  72.  
  73. // Create the header to be used - Add username and password
  74. self.makeURLRequest()
  75. self.addPreAuthentication(username, password)
  76.  
  77. // Make the request for the token
  78. Alamofire.download("(UrlHelper.buildUrlFrom(SettingsManager.serverURL)), method: .post, parameters: nil, headers: self.request.allHTTPHeaderFields, to: destination)
  79. // Alamofires built in authentication will provide credentials when challenged for authentication
  80. .authenticate(user: username, password: password)
  81. .responseString(
  82. queue: queue,
  83. completionHandler: { response in
  84.  
  85. DispatchQueue.main.async {
  86. switch response.result {
  87. // If the result was successful, the token string is saved to a file
  88. case .success:
  89. // Uncomment to see token string value
  90. //debugPrint("Value (response.value!)")
  91. completionHandler()
  92. case .failure(let error):
  93. debugPrint("Failed (error)")
  94. }
  95. }
  96. }
  97. )
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement