URLSession, willPerformHTTPRedirection and timeouts

Erk. It’s been a month since I started this thing and I haven’t updated it in a while. I’ve been busy on other stuff at the lab, but have been plugging away at bits and pieces when I can find the time. Lately, I’ve been trying to replicate the Fetch API in iOS. The first hacky version kind of sidestepped the details of the API and just downloaded whole files into memory, but we want to be a little smarter than that, since we might be downloading multi-megabyte files into our cache, or something like that.

But anyway, more on that when it’s actually done. In the meantime, a very quick note about an infurating bug I (think I) stumbled upon. The Fetch API has a redirect attribute that lets you control whether your request follows redirects or not. iOS’s URLSessionTaskDelegate has a method called willPerformHTTPRedirection that lets you control this, via an asynchronous completion handler - you either pass the new, redirected request to it, or pass nothing - if you pass nothing it’ll just return the unredirected response.

Expect it won’t always. The first time you run it, it will. The second time it just hangs until the request times out. You might be able to imagine how confusing this was when running my test suite. It appears someone has already filed a bug report but in the meantime I have the Fetch implementation manually setting the URLRequest.CachePolicy to reloadIgnoringLocalCacheData when redirect is set to manual, which seems to restore the behaviour we expect, even if it isn’t using the cache.

Anyway, hopefully someone will stumble across this post when they put some of these terms into Google and save themselves some of the time I wasted working out what was going on here!

Written on July 14, 2017