Can AFNetworking 2 store the cookies

2019-05-11 21:02发布

I used AFHTTPClient and seems it stored cookies in the box. So when I was logged in. and then reload my app, the cookies were in application automatically. Maybe I confused about this. But seems it works in the way I described.

Now I use this code:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    [manager POST:path parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {  
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    }];

But when I restart my application I get message with wrong token when I try request some of my api method.

So how can I store my cookies using the code above. I use this code for all my request for login, logout and other api services. If I don't restart it works good, but i rerun it seems cookies are went from me.

How can I solve this?

I found this answer link but I am not sure how to use it.

I have checked cookies.

If I don't rerun application the cookies are the same:

<NSHTTPCookie version:0 name:"...." value:"....." expiresDate:(null) created:2014-02-27 19:24:29 +0000 (4.15222e+08) sessionOnly:TRUE domain:"...." path:"/" isSecure:FALSE>

But if I rerun app the cookie are changed.

Oh I understood, the app does not save cookies, seems I need to write this functional. Do you have good suggestion how to do it?

1条回答
孤傲高冷的网名
2楼-- · 2019-05-11 22:03

From Persisting Cookies in an iOS Application:

Cookies without an expiry date are considered 'session only' and will get cleared when you restart the app. You can check the 'session only' situation via a BOOL property in NSHTTPCookie. This is standard cookie stuff and not something specific to iOS.

AFNetworking does not do anything with cookies under the hood. It does use NSURLConnection, and NSURLConnection uses NSHTTPCookieStorage.

According to your log:

<NSHTTPCookie version:0 name:"...." value:"....." expiresDate:(null) created:2014-02-27 19:24:29 +0000 (4.15222e+08) sessionOnly:TRUE domain:"...." path:"/" isSecure:FALSE>

you have session only cookies ("sessionOnly:TRUE").

You need to add an expiration date on the server end so that NSHTTPCookieStorage doesn't throw them away when your session ends.

This is not anything AFNetworking-specific; it's just how cookies work.

查看更多
登录 后发表回答