How to track URLSessionTask after Alamofire retries the request

461 Views Asked by At

We are using Alamofire 4 and want to match URLSessionTasks to entities in a database.

We first used the taskDescription field of URLSessionTask to put UUID of a database entity there, but then figured out that Alamofire creates a new task on request retry and this field is not copied over. taskIdentifier also changes with every new task created, and there seem to be no way to track the change of taskIdentifier in Alamofire.

Are there any other techniques to match tasks and entities in a database or files? The end goal is to delete file + entity if background upload request succeeds. And that might happen after the app has been terminated, thus we currently store information in a database.

1

There are 1 best solutions below

0
On BEST ANSWER

Assuming AlamoFire isn't doing something nutty, you should be able to do something like this:

NSString *const identifierProperty = @"com.you.yourProduct.requestID";
NSString *myIdentifier = [NSUUID UUID].UUIDString;
[NSURLProtocol setProperty:myIdentifier
                     inKey:identifierProperty
                  inRequest:theURLRequest];

and then, later, to get it back:

NSString *requestID = [NSURLProtocol propertyForKey:identifierProperty
                                          inRequest:theURLRequest];

Apologies for the Objective-C, but it should be easily convertible to Swift.

Once you do that, the property should be copied whenever the request is copied, just like any first-class property on the request. You might even consider creating a category on NSURLRequest to expose the underlying value as an actual native property.