Modern browsers work differently from older ones -- they want to save your page off-screen, or "cache" it, rather than unload it completely. In some browsers, your use of "onunload" or "onbeforeunload" rules out caching, leading to slower performance for your site. Safari on iOS, on the other hand, caches the page anyway and just ignores your script!
The solution is simple. In place of "onunload" or "onbeforeunload," use "onpagehide." That's right, just substitute that one term for either of the other two. Then your script will be triggered whenever the page is unloaded OR just cached. Not only will Safari now write your cookies, but this will speed up navigation back to your page in all other modern browsers!
By the same token, you may want to replace "onload" with "onpageshow." But not always. "Onpageshow" will trigger whenever a page is loaded OR just retrieved from cache. But if the page is just retrieved, it returns in its previous state, so onload functions may not be needed or wanted. In that case, you should leave those functions in "onload," while moving any others to "onpageshow."