HttpClient.swift 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. // _____ _
  2. // |_ _| |_ _ _ ___ ___ _ __ __ _
  3. // | | | ' \| '_/ -_) -_) ' \/ _` |_
  4. // |_| |_||_|_| \___\___|_|_|_\__,_(_)
  5. //
  6. // Threema iOS Client
  7. // Copyright (c) 2018-2020 Threema GmbH
  8. //
  9. // This program is free software: you can redistribute it and/or modify
  10. // it under the terms of the GNU Affero General Public License, version 3,
  11. // as published by the Free Software Foundation.
  12. //
  13. // This program is distributed in the hope that it will be useful,
  14. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. // GNU Affero General Public License for more details.
  17. //
  18. // You should have received a copy of the GNU Affero General Public License
  19. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. import Foundation
  21. public class HttpClient {
  22. public enum ContentType {
  23. case json
  24. case octetStream
  25. func propertyValue() -> String {
  26. switch self {
  27. case .json:
  28. return "application/json"
  29. case .octetStream:
  30. return "application/octet-stream"
  31. }
  32. }
  33. }
  34. private static let bgSessionsMutationLock: DispatchQueue = DispatchQueue(label: "bgSessionsMutationLock")
  35. private static var bgSessions: [Int: URLSession] = [Int: URLSession]()
  36. public init() { }
  37. public func delete(url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Swift.Void) {
  38. let request = getRequest(url: url, httpMethod: "DELETE")
  39. let task = getSession(delegate: nil).dataTask(with: request, completionHandler: completionHandler)
  40. task.resume()
  41. }
  42. public func downloadData(url: URL, contentType: ContentType, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Swift.Void) -> Void {
  43. var request = getRequest(url: url, httpMethod: "GET")
  44. request.setValue(contentType.propertyValue(), forHTTPHeaderField: "Accept")
  45. let task = getSession(delegate: nil).dataTask(with: request, completionHandler: completionHandler)
  46. task.resume()
  47. }
  48. public func downloadData(url: URL, delegate: URLSessionDelegate) -> Void {
  49. var request = getRequest(url: url, httpMethod: "GET")
  50. request.setValue("application/octet-stream", forHTTPHeaderField: "Accept")
  51. let task = getSession(delegate: delegate).dataTask(with: request)
  52. task.resume()
  53. }
  54. public func uploadData(url: URL, data: Data, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Swift.Void) -> Void {
  55. var request = getRequest(url: url, httpMethod: "PUT")
  56. request.setValue(ContentType.octetStream.propertyValue(), forHTTPHeaderField: "Content-Type")
  57. let task = getSession(delegate: nil).uploadTask(with: request, from: data, completionHandler: completionHandler)
  58. task.resume()
  59. }
  60. public func uploadData(url: URL, file: URL, delegate: URLSessionDelegate) -> Void {
  61. var request = getRequest(url: url, httpMethod: "PUT")
  62. request.setValue(ContentType.octetStream.propertyValue(), forHTTPHeaderField: "Content-Type")
  63. let task = getSession(delegate: delegate).uploadTask(with: request, fromFile: file)
  64. task.resume()
  65. }
  66. private func getRequest(url: URL, httpMethod: String) -> URLRequest {
  67. var request = URLRequest(url: url, cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 900)
  68. request.httpMethod = httpMethod
  69. return request
  70. }
  71. private func getSession(identifier: Int, delegate: URLSessionDelegate) -> URLSession {
  72. var bgSession: URLSession? = nil
  73. HttpClient.bgSessionsMutationLock.sync {
  74. if let session = HttpClient.bgSessions[identifier] {
  75. bgSession = session
  76. } else {
  77. let configuration = URLSessionConfiguration.background(withIdentifier: String(identifier))
  78. configuration.allowsCellularAccess = true
  79. configuration.sessionSendsLaunchEvents = true
  80. if #available(iOSApplicationExtension 11.0, *) {
  81. configuration.waitsForConnectivity = true
  82. }
  83. let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
  84. HttpClient.bgSessions[identifier] = session
  85. bgSession = session
  86. }
  87. }
  88. return bgSession!
  89. }
  90. private func getSession(delegate: URLSessionDelegate?) -> URLSession {
  91. if let delegate = delegate {
  92. let objectHash: Int = delegate.hash
  93. return getSession(identifier: objectHash, delegate: delegate)
  94. }
  95. URLSession.shared.configuration.allowsCellularAccess = true
  96. if #available(iOSApplicationExtension 11.0, *) {
  97. URLSession.shared.configuration.waitsForConnectivity = true
  98. }
  99. return URLSession.shared
  100. }
  101. }