iphone NSHTTPCookieStorage avaible on app reopen? - iphone

I am working on my app here- and it pretty much comes to this. I have a login box where a users log's in and then it saves the cookie data on return like so:
NSArray * all = [NSHTTPCookie cookiesWithResponseHeaderFields:[resp allHeaderFields] forURL:[NSURL URLWithString:#"http://myurl]];
NSHTTPCookieStorage *sharedHTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
[sharedHTTPCookieStorage setCookies:all forURL:[NSURL URLWithString:#"http://myurl"] mainDocumentURL:nil];
After it safes that cookie i take it to the home view - My problem is - if the users closes the prgoram, the phone restarts and so forth - are the cookies stored locally on the phone its sefl? I am trying to access that cookie again on the didFinishLaunchingWithOptions. I have the following code now..
NSHTTPCookieStorage *sharedHTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray *cookies = [sharedHTTPCookieStorage cookiesForURL:[NSURL URLWithString:#"http://iphone.wazgood.com"]];
NSLog(#"count: %i", [cookies count]);
Every time - it comes up empty on the cookie data - any ideas on if the cookies are cleared every time the user clsoes the program out - or is it bc im testing on the iPhone emulator?

In case you or anyone else is still having this problem, it could be that the cookies are set to expire when the session ends (when the app closes). You can check for this behavior by looking at the sessionOnly property of your NSHTTPCookies (the getter method is -(BOOL)isSessionOnly).

Related

Cookie from ios webview

I wanted to ask some things about a piece of code i'm trying to make without having any previous contact with ios or objective-c.
This piece of code will:
Open a WebView with a specific url where the user will login
(done)
After the user logs in it will take the cookie created
from that login.
It will use that cookie in a next request to
load another site that requires authentication.
I'm stuck a bit at part 2 because it has to a) wait in another thread till the user does the login (how?) and b) because i can't seem to get the specific cookie for the site easily. I have only found and tried this poc but how do I filter out only the cookie for the site I want?
NSHTTPCookie *cookie;
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for(cookie in [cookieJar cookies]) {
NSLog(#"%#", cookie);
}
Any ideas on how to make the 2a/b parts? Objective-c syntax seems a bit confusing.
I found a solution by following this https://www.inkling.com/read/learning-ios-programming-alasdair-allan-2nd/chapter-7/embedding-a-web-browser-in-your .
Used the webViewDidFinishLoad delegate and got the cookies from there with the cookiesForURL method.
NSArray* availableCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:#"MYURL"]];
Cookies are created as follows,
NSDictionary *properties = [NSDictionary dictionaryWithObjectsAndKeys:
url, NSHTTPCookieOriginURL,
#"testCookies", NSHTTPCookieName,
#"1", NSHTTPCookieValue,
nil];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:properties];
You can use the cookie object to get the origin URL attribute and filter.
NSDictionary *cookieProperties = [cookie properties];
NSURL *originURL = [cookieProperties objectForKey:NSHTTPCookieOriginURL];
After filtering the cookie you need you can get the cookie value using,
cookie.value

logout from facebook completely

I have integrated facebook SDK and able to login to facebook. If user is enabled with facebook account on iOS settings then it ask for permission to acces in app otherwise it goes to safari for facebook login and come back to app. For logout I used following code:
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies])
{
NSString* domainName = [cookie domain];
NSRange domainRange = [domainName rangeOfString:#"facebook"];
if(domainRange.length > 0)
{
[storage deleteCookie:cookie];
}
}
[FBSession.activeSession closeAndClearTokenInformation];
But it is unable to logout completely. If I again click the login button it still showing access token as well as not moving to safari for facebook login again it means it has not logged out completely from facebook. I am unable to recognized the issue. If anyone know about this please help me out.
I would be very thankful to you.
Are you using version 3.x of the Facebook SDK for iOS? If so, the FBSession class should have a method called
-[FBSession closeAndClearTokenInformation]
Hopefully this will work for you.

Unable To Logout of Facebook using Socialize SDK

I am using Socialize SDK in lieu of Sharekit to integrate mail, twitter and facebook in my app.
I only need to post some string on the user's profile which is working fine for facebook and twitter.
Following is the workflow:
User clicks on share , selects facebook/twitter.
If it is for the first time user is sharing, facebook/twitter login screen pops up
User Logs in and after authentication, share is successful.
If user shares for the second time, facebook/twitter login screen doesn't popsup for authentication and the share is successful.
If user wants to logout of facebook/twitter, he goes to the settings panel and clicks on twitter / facebook button to logout.
[When it goes back to share after log gin out, user clicks on twitter , login screen pops up but when user clicks on facebook, a shadow box appears for few seconds and disappears and user is logged in with the previous account. ]
How would i resolve this issue ?
I have tried using
[SocializeThirdPartyFacebook removeLocalCredentials] and also
[SZFacebookUtils unlink];
how should i go about it
I tried Clearing all the cache and cookies as well but still the same result
NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray* facebookCookies = [cookies cookiesForURL:
[NSURL URLWithString:#"http://login.facebook.com"]];
for (NSHTTPCookie* cookie in facebookCookies) {
NSLog(#"In For");
[cookies deleteCookie:cookie];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults removeObjectForKey:kSocializeFacebookAuthAppId];
[defaults removeObjectForKey:kSocializeFacebookAuthLocalAppId];
[defaults removeObjectForKey:kSocializeFacebookStringForAPI];
[defaults removeObjectForKey:kSocializeConsumerKey];
[defaults removeObjectForKey:kSocializeConsumerSecret];
Facebook and twitter SDK save access token in cookies.
So you have to clear all cache and cookies when you are trying to use logging mechanism in your code.
I solved it:
1.In the advance settings of the app on facebook, i enabled native/desktop app
2.Disabled SSO in basic settings
3.Added de-auth callback url in advance settings
4.Added the following piece of code:
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies])
{
NSString* domainName = [cookie domain];
NSRange domainRange = [domainName rangeOfString:#"facebook"];
if(domainRange.length > 0)
{
[storage deleteCookie:cookie];
}
}

deleted NSHTTPCookie returns if app is terminated

After using some code to delete all of the cookies:
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies]) {
[storage deleteCookie:cookie];
}
if you continue to use the app for a period of time, the cookies stay deleted. however, if you terminate the app immediately afterwards, the cookies will come back. sounds like some kind of cookie sync mechanism isn't kicking in fast enough, but the's no mention of it in the HTTPCookieStore docs.
How do you get a cookie to (reliably) stay deleted?
I do not think that there is a way to do that. Cookies are cached before they are sent to the NSHTTPCookie class and the same thing happens when you delete cookies. The class is told to delete the Cookies on quit, but won't if the app crashes as it doesn't catch the appropriate event.

Reading cookies using xcode on the iphone [duplicate]

Can an iPhone application read cookies previously stored by Safari Mobile?
To actually answer your question:
No.
Mobile Safari's cookies are not accessible from SDK apps. And each SDK app is given its own WebKit cache and cookie stores, so while cookies will persist within the same app, they aren't accessible betweeen apps.
As of iOS 9 this is possible!
Use a sfSafariViewController.
You will need to setup:
A custom URL scheme in your app to receive cookie data.
The website you are getting cookies from will need to implement an API specific your app's custom URL scheme, to redirect back to your app.
You can clone this repo which has a fully working demo of this.
Hope this helps,
Liam
There is actually an interesting way if you have access to a server url.
In your app launch the server url with mobile safari.
The target server url reads the cookie and redirects back to an app specific url (myapp://cookie=123)
The app is then switched back and you can read that value from the url handler
It's a little hacky as the app would switch mobile safari and then immediately switch back to the app. But, it is possible.
Note that on iOS 8, you're probably better using Safari Password Sharing to solve some of the use cases that give rise to this problem.
This is not directly possible, but with the cooperation of the web site it is possible.
To clarify, the user case is that an Objective C application wants to read the value of a cookie that has been set by a website in mobile safari. (ie. in particular, a UIWebView was not involved in setting the cookie)
Your app should do this:
Launch mobile safari, using [[UIApplication sharedApplication] openURL:url];
The URL should be a special one, eg. http://yourwebsite.com/give-ios-app-the-cookie
On your website, when that url is launched, issue a redirect to your-app-url-scheme:cookievalue= (eg. angrybirds:cookievalue=hh4523523sapdfa )
when your app delegate receives - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation process the url to get the cookie value
Note that you should not do this automatically when the application starts - the user will see the transfer to Mobile Safari and back, which is not a good user experience and Apple will reject your app (Apple also consider this to be "uploading user's personal data to server without their prior consent"). It would be better to do it in response to the user, paying attention to the user experience - eg. wait for the user to hit a "login" button, then do it, and if the user is not logged into your website, http://yourwebsite.com/give-ios-app-the-cookie should show the user the login screen within safari. If the user is logged in you could briefly show a "Automatically logging you in..." screen for a second or two in Safari before redirecting the user back.
There's no way to get this to work with hotmail/gmail/etc of course - it needs to be your own website.
Credit goes to Unique Identifier for both mobile safari and in app in iOS for suggesting this kind of approach.
Because of sandboxing on the iPhone you don't have access to Safari's cookies. You can only access cookies created within your application - by an UIWebView for example.
Although you have asked the same question twice before, here's one approach not yet mentioned...
This may be a little convoluted, but you can do Greasemonkey-esque things with a UIWebView. Something like this:
Load your target page
craft some javascript which will read the document.cookie and return the data you need
In the webViewDidFinishLoad delegate, inject this javascript into the UIWebView with the stringByEvaluatingJavaScriptFromString message
I've used this technique to enhance 3rd party pages in an iPhone app, but I'm not sure if it will read cookies from the same place as Safari mobile.
Worth a shot though?
Here's my utils get/set cookie methods.
+(void)setCookie:(NSString *)key withValue:(NSString *)value {
NSArray *keys = [NSArray arrayWithObjects:
NSHTTPCookieDomain,
NSHTTPCookieExpires,
NSHTTPCookieName,
NSHTTPCookiePath,
NSHTTPCookieValue, nil];
NSArray *objects = [NSArray arrayWithObjects:
#"YOURDOMAIN",
[NSDate distantFuture],
key,
#"/",
value, nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:dict];
NSHTTPCookieStorage *sharedHTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
[sharedHTTPCookieStorage setCookie:cookie];
}
+(NSString *)getCookie:(NSString *)key {
NSHTTPCookieStorage *sharedHTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray *cookies = [sharedHTTPCookieStorage cookiesForURL:[NSURL URLWithString:#"YOURDOMAIN"]];
NSEnumerator *enumerator = [cookies objectEnumerator];
NSHTTPCookie *cookie;
while (cookie = [enumerator nextObject])
{
if ([[cookie name] isEqualToString:key])
{
return [cookie value];
}
}
return nil;
}
You might want to check
if ([[NSHTTPCookieStorage sharedHTTPCookieStorage] cookieAcceptPolicy] != NSHTTPCookieAcceptPolicyAlways) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
}
But apparently NSHTTPCookieStorage does not even hold cookies from the last request in the current application on iOS (rdar://8190706)