Setting a cookie in an iPhone App

后端 未结 4 2119
有刺的猬
有刺的猬 2020-12-03 06:14

Is it possible to set a cookie in an iPhone Application that persists, so that later when the user is in Mobile Safari, that cookie can be sent to a webserver?

4条回答
  •  悲哀的现实
    2020-12-03 06:53

    ** Update 2017 **
    A lot of changes to security mechanisms and cross-app communication were introduced to iOS in the recent years since this was first answered.

    The below code no longer works on current iOS releases since Safari no longer accepts javascript:... in URLs and frameworks like NSURL catch these and return nil.

    The one alternative that still works is to either host a website and have Safari open it or integrate such a HTML page in your app and run a small http server to host it on demand.

    **iOS up to 6.x **
    Since Apple has forced the sandboxing on all app store applications
    there's currently no easy way to realize your request.

    You could however open a special http://-URL from your application containing javascript to place a cookie:

    NSString jsURL = @"javascript:function someFunction(){ /* your javascript code here */ } someFunction();void(0)";
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString: jsURL]];
    

    Using javascript in URLs has been used by different iPhone applications to cross communicate
    with MobileSafari (for example instapaper).

    Another option would be to include a static HTML page in your app or on your server and instruct MobileSafari to open it.
    The page in turn could set the permanent cookie.

    Hope this helps!

提交回复
热议问题