i have used the singleton pattern for networking call but one issues is faced can anyone help me to solved this issue the session was invalidated
Session was invalidated without error, so it was likely deinitialized unexpectedly. Be sure to retain a reference to your Session for the duration of your requests.
and my networking wrapper is
public static let shared = NetworkingClient()
private var requests = [ApiRequest]()
private var completedRequests = 0
private var session: Session!
func InvalidateSession () {
if #available(iOS 9.0, *) {
Alamofire.Session.default.session.getAllTasks { (tasks) in
tasks.forEach{ $0.cancel() }
}
} else {
Alamofire.Session.default.session.getTasksWithCompletionHandler { (sessionDataTask, uploadData, downloadData) in
sessionDataTask.forEach { $0.cancel() }
uploadData.forEach { $0.cancel() }
downloadData.forEach { $0.cancel() }
}
}
}
This is my Api Call the secanrio is increase quantity then crash the alomofire i want to stop the send request multiple request i want to send request api only 1 time
func gasEstimation(chain_Id: Int, contractAddress: String, fromAddress: String, toAddress: String, tokenId: String, contractType: String, quantity: String) {
let apiRequest = [ApiRequest(type: .get, path: "gasEstimation?chainId=\(chain_Id)&contractAddress=\(contractAddress)&from=\(fromAddress.trimmingCharacters(in: .whitespacesAndNewlines))&to=\(toAddress.trimmingCharacters(in: .whitespacesAndNewlines))&type=\(contractType)&quantity=\(quantity)&tokenId=\(tokenId)")]
NetworkingClient.shared.performRequest(requests: apiRequest) { path, data, error in
if data != nil {
let json = JSON(data!)
let gasTokenModel = NftTransferModel(json: json)
self.presenter?.onReceiveFee(estimationFee: gasTokenModel,error: nil)
}else{
let error = JSON(error!)
self.presenter?.onReceiveFee(estimationFee: nil,error: error["message"].stringValue)
}
}
}
There are a few issues here.
Session!indicates you're operating on an optional value, which seems unnecessary. Also, if you're replacing this value, this is likely the cause of the invalidation error, as theSessionthat was replaced will invalidate when it's deinited.private var session: Session!, yet you useSession.defaultto cancel all of your requests. This is incorrect, you need to cancel requests on your localsession.URLSessioninstance directly. Instead,Sessionhas acancelAll()method you can use to do the same thing.Decodablefor your JSON parsing, it's far simpler and Alamofire has built-in support for it.