Last active
August 23, 2017 09:57
-
-
Save joshtwist/4422230 to your computer and use it in GitHub Desktop.
Using a filter in an iOS / Objective-C application to automatically log a user back into the Mobile Service if any request returns a 401 (for example, due to a timeout of the token).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // This is the MSFilter protocol implementation taken from the iOS Mobile Services'\ | |
| // quickstart and modified to log the user in if a 401 Unauthorized response is received | |
| #pragma mark * MSFilter methods | |
| - (void) handleRequest:(NSURLRequest *)request | |
| onNext:(MSFilterNextBlock)onNext | |
| onResponse:(MSFilterResponseBlock)onResponse | |
| { | |
| // Increment the busy counter before sending the request | |
| [self busy:YES]; | |
| onNext(request, ^(NSHTTPURLResponse *response, NSData *data, NSError *error){ | |
| [self filterResponse:response | |
| forData:data | |
| withError:error | |
| forRequest:request | |
| onNext:onNext | |
| onResponse:onResponse]; | |
| }); | |
| } | |
| - (void) filterResponse: (NSHTTPURLResponse *) response | |
| forData: (NSData *) data | |
| withError: (NSError *) error | |
| forRequest:(NSURLRequest *) request | |
| onNext:(MSFilterNextBlock) onNext | |
| onResponse: (MSFilterResponseBlock) onResponse | |
| { | |
| if (response.statusCode == 401) { | |
| // do login | |
| [self.client loginWithProvider:@"twitter" onController:[[[[UIApplication sharedApplication] delegate] window] rootViewController] animated:YES completion:^(MSUser *user, NSError *error) { | |
| if (error && error.code == -9001) { | |
| // user cancelled authentication - return the original response | |
| [self busy:NO]; | |
| onResponse(response, data, error); | |
| return; | |
| } | |
| NSMutableURLRequest *newRequest = [request mutableCopy]; | |
| [newRequest setValue:self.client.currentUser.mobileServiceAuthenticationToken forHTTPHeaderField:@"X-ZUMO-AUTH"]; | |
| onNext(newRequest, ^(NSHTTPURLResponse *innerResponse, NSData *innerData, NSError *innerError){ | |
| [self filterResponse:innerResponse | |
| forData:innerData | |
| withError:innerError | |
| forRequest:request | |
| onNext:onNext | |
| onResponse:onResponse]; | |
| }); | |
| }]; | |
| } | |
| else { | |
| [self busy:NO]; | |
| onResponse(response, data, error); | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'd love suggestions on how to make this code more elegant!