iPhone NSData/NSUrl with cookie

2019-02-15 15:23发布

问题:

I'm trying to play/stream a mp3 hosted on a website. The site requires a cookie header to be set, but I'm having trouble setting that or getting the container to do that for me.

 NSURL *sampleUrl = [NSURL URLWithString:@"http://domain/files/sample.mp3"];
 NSData *sampleAudio = [NSData dataWithContentsOfURL:sampleUrl];

Up until this point, I've been using jQuery to do/manage XMLHTTPRequests, but I've had to call into native code to stream the audio. It doesn't look like the cookie is getting picked up by the native HTTP request.

Is there anyway to inject the cookie into the above request, or otherwise ensure that a cookie gets added against a given domain?

Thanks

回答1:

Ok, so the way to do this is not injecting headers but setting a cookie manager to always accept cookies. This will then pass on the cookie to subsequent requests.

    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    [cookieStorage setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];

Robbie