I'm having issue loggingout of my Localhost which is implemented by using Drupal 7
I've configured everything as mentioned by https://github.com/kylebrowning/drupal-ios-sdk
First of all, I wanna thank kylebrowning for spending his huge amount of time to create this awesome SDK.
The problem that i'm facing is that I can login just fine, but I failed logout.
I NSLog to see the error of the code.
Here is the error that shows on the out put tab.
I don't have enough reputation to post more than two links
here is what inside my http below, "192.168.1.24/drupal/rest/user/logout"
Domain=AFNetworkingErrorDomain Code=-1011 "Expected status code in (200-299), got 401" UserInfo=0x8c4d6c0 {NSLocalizedRecoverySuggestion=["CSRF validation failed"], AFNetworkingOperationFailingURLRequestErrorKey= { URL: ">" http:// }, NSErrorFailingURLKey=http:, NSLocalizedDescription=Expected status code in (200-299), got 401, AFNetworkingOperationFailingURLResponseErrorKey= { URL: http:// } { status code: 401, headers {
"Cache-Control" = "no-cache, must-revalidate, post-check=0, pre-check=0";
Connection = "Keep-Alive";
"Content-Length" = 26;
"Content-Type" = "application/json";
Date = "Thu, 27 Mar 2014 09:10:32 GMT";
Etag = "\"1395911432\"";
Expires = "Sun, 19 Nov 1978 05:00:00 GMT";
"Keep-Alive" = "timeout=5, max=98";
"Last-Modified" = "Thu, 27 Mar 2014 09:10:32 +0000";
Server = "Apache/2.2.25 (Unix) mod_ssl/2.2.25 OpenSSL/0.9.8y DAV/2 PHP/5.5.3";
"Set-Cookie" = "SESS0fd8593946486e6ecd06721db47d9fe9=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/; httponly";
Vary = Accept;
"X-Powered-By" = "PHP/5.5.3";
} }}
Here is my code
#import "AfterLoginViewController.h"
#import "DIOSUser.h"
#import "DIOSSession.h"
#import "DIOSSystem.h"
#interface AfterLoginViewController ()
#end
#implementation AfterLoginViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (IBAction)LogOut {
[DIOSUser
userLogoutWithSuccessBlock:^(AFHTTPRequestOperation *op, id response)
{
[self alertStatus:#"Logout Successful" :#"Sign Out Successful" :0];
NSLog(#"Logout Successful");
[self alertStatus:#"LogOut Successful" :#"LogOut is completed" :0];
[self performSegueWithIdentifier:#"BackToLogin" sender:self];
/* Handle successful operation here */
}
failure:^(AFHTTPRequestOperation *op, NSError *err)
{
[self alertStatus:#"LogOut Failed" :#"LogOut failed Please Try Again !!!" :0 ];
NSLog (#"Signout failed");
NSLog (#"%#", err);
}
];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void) alertStatus:(NSString *)msg :(NSString *)title :(int) tag
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
message:msg
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
alertView.tag = tag;
[alertView show];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
I would be very appreciated if someone can help me out with this issue.
Find in DIOSSystem class
this method
+ (void)systemConnectwithSuccess: (void (^)(AFHTTPRequestOperation *operation, id responseObject)) success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error)) failure {
DIOSSession *session = [DIOSSession sharedSession];
[session getCSRFTokenWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {...}
and check if in getCSRFTokenWithSuccess the token is setted correctly like:
- (void)getCSRFTokenWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#/services/session/token", [[DIOSSession sharedSession] baseURL]]]];
[request setValue:[NSString stringWithFormat:#"text/plain"] forHTTPHeaderField:#"Accept"];
AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *aCsrfToken = [NSString stringWithUTF8String:[responseObject bytes]];
[[DIOSSession sharedSession] setCsrfToken:aCsrfToken];
if (success != nil) {
success(operation, responseObject);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[DIOSSession logRequestFailuretoConsole:operation withError:error];
if (failure != nil) {
failure(operation, error);
}
}];
operation.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"text/plain", #"application/json", nil];
operation.responseSerializer = [AFHTTPResponseSerializer serializer];
[self.operationQueue addOperation:operation];
}
Finally use this , works for me:
[DIOSUser
userMakeSureUserIsLoggedOutWithSucess:^(AFHTTPRequestOperation *op, id response) {
NSLog(#"LogOut success!");
}
failure:^(AFHTTPRequestOperation *op, NSError *err) {
NSLog(#"LogOut error: %#",err);
}
];
Related
This issue is intermittent and I have no idea why this is happening. Basically, I am trying to add a new post by sending a POST request to a remote RESTful API. I checked with POSTMAN that there is no problem with the API at all, but AFNetworking seems to fail some of its requests for no reason.
Here's my complete code:
- (IBAction)doneButtonPressed:(id)sender {
NSString *postBody = self.postInputField.text;
NSDictionary *params = #{#"postBody": postBody};
NetworkManager *manager = [NetworkManager sharedNetworkManager];
[manager POST:NEW_POST_API_URL parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"NewPostSuccess. resp: %#", responseObject);
[[NSNotificationCenter defaultCenter] postNotificationName:ASK_TO_ADD_POST_ROW object:responseObject userInfo:nil];
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSString* ErrorResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
NSLog(#"%#", ErrorResponse);
}];
[self dismissViewControllerAnimated:YES completion:^{
[[NSNotificationCenter defaultCenter] postNotificationName:TABLE_SCROLL_TO_TOP object:nil userInfo:nil];
}];
}
and here is the error:
com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x170429b40> { URL: http://192.168.0.102:3000/api/posts/new } { status code: 503, headers {
Connection = "keep-alive";
"Content-Type" = "text/plain";
Date = "Mon, 05 Oct 2015 03:15:37 GMT";
"Transfer-Encoding" = Identity;
} }, NSErrorFailingURLKey=http://192.168.0.102:3000/api/posts/new, com.alamofire.serialization.response.error.data=<556e6578 70656374 65642065 72726f72 2e>, NSLocalizedDescription=Request failed: service unavailable (503)}
task: <__NSCFLocalDataTask: 0x136e6b150>{ taskIdentifier: 10 } { completed }
This happens intermittently, where I change nothing in the code and it starts working again in the same viewcontroller. The response error is useless as it only says unexpected error. Any guidance will be hugely appreciated.
I am having an issue where I am not able to connect to the API. This happens only with iOS8. It works fine with iOS7.
- (void)performSearch:(NSString*)type : (NSString*)keyword{
url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#", API, keyword]];
request = [NSURLRequest requestWithURL:url];
operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
credential = [NSURLCredential credentialWithUser:USERNAME password:PASSWORD persistence:NSURLCredentialPersistenceForSession];
[operation setCredential:credential];
[[NSOperationQueue mainQueue] addOperation:operation];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError *error = nil;
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
if (error) {
NSLog(#"Error serializing %#", error);
return;
}
[self parseJSON:JSON :keyword];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error : %#", error);
}];
[operation start];
}
The Error message I am getting.
Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: unauthorized (401)" UserInfo=0x7ff0650052f0 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x7ff062c5e4d0> { URL: https://distribution.virk.dk/cvr-permanent-prod-20150622/_search?q=anders } { status code: 401, headers {
Connection = "keep-alive";
"Content-Length" = 194;
"Content-Type" = "text/html";
Date = "Tue, 18 Aug 2015 09:36:09 GMT";
Server = "nginx/1.6.2";
"Www-Authenticate" = "Basic realm=\"Beskyttet adgang\"";
} }, NSErrorFailingURLKey=https://distribution.virk.dk/cvr-permanent-prod-20150622/_search?q=anders, com.alamofire.serialization.response.error.data=<3c68746d 6c3e0d0a 3c686561 643e3c74 69746c65 3e343031 20417574 686f7269 7a617469 6f6e2052 65717569 7265643c 2f746974 6c653e3c 2f686561 643e0d0a 3c626f64 79206267 636f6c6f 723d2277 68697465 223e0d0a 3c63656e 7465723e 3c68313e 34303120 41757468 6f72697a 6174696f 6e205265 71756972 65643c2f 68313e3c 2f63656e 7465723e 0d0a3c68 723e3c63 656e7465 723e6e67 696e782f 312e362e 323c2f63 656e7465 723e0d0a 3c2f626f 64793e0d 0a3c2f68 746d6c3e 0d0a>, NSLocalizedDescription=Request failed: unauthorized (401)}
Status code is 401, which means that your account or password is incorrect. I suggest that you should log out the params, and find out whether they are null or anything else
I’m trying to get messages list from gmail on iOS. I successfully received access token (using OAuth 2.0) to my account. But the next i have to do is get messages list using exactly AFNetworking framework (that’s the aim). Tried to do everything i could just like here: Google API Users.messages: list but i got an error :
Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: forbidden (403)" UserInfo=0x8e5f9b0 {com.alamofire.serialization.response.error.response= { URL: .../gmail/v1/users/me/messages } { status code: 403, headers {
"Alternate-Protocol" = "443:quic,p=1";
"Cache-Control" = "private, max-age=0";
"Content-Encoding" = gzip;
"Content-Type" = "application/json; charset=UTF-8";
Date = "Tue, 28 Jul 2015 10:54:07 GMT";
Expires = "Tue, 28 Jul 2015 10:54:07 GMT";
Server = GSE;
"Transfer-Encoding" = Identity;
Vary = "Origin, X-Origin";...
Here is my code:
#import "RSServerManager.h"
#import "AFNetworking.h"
#import "RSUser.h"
#import "RSAccessToken.h"
#interface RSServerManager()
#property (strong, nonatomic) AFHTTPRequestOperationManager *requestOperationManager;
#end
#implementation RSServerManager
+ (RSServerManager *) sharedManager {
static RSServerManager *manager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [[RSServerManager alloc] init];
});
return manager;
}
- (id)init
{
self = [super init];
if (self) {
NSURL *url = [NSURL URLWithString:#"https://www.googleapis.com/"];
self.requestOperationManager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:url];
}
return self;
}
GET method:
- (void) getMessagesList:(RSAccessToken *)accessToken
onSuccess:(void (^)(__autoreleasing id *))success
onFailure:(void (^)(NSError *, NSInteger))failure {
NSDictionary *Parameters = [NSDictionary dictionaryWithObjectsAndKeys:
#"messages", #"fields",
#"true", #"includeSpamTrash",
#"https://mail.google.com/", #"scope",
#"query", #"q",nil];
AFHTTPRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
NSString *authValue = [NSString stringWithFormat:#"Bearer %#", accessToken.access_token];
[requestSerializer setValue: authValue forHTTPHeaderField:#"Authorization"];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
self.requestOperationManager.requestSerializer = requestSerializer;
[self.requestOperationManager
GET:#"gmail/v1/users/me/messages"
parameters: Parameters
success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
NSLog(#"JSON : %#", responseObject);
if (success) {
success(nil);
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
if (failure) {
failure(error, operation.response.statusCode);
}
}];
}
Please help me to find the correct way to get these message list using AFNetworking!!!
Enable Gmail-API in your developers console. Include one of the scopes mentioned in this link in your code.
I want to use the Instagram API, and I downloaded this project from link, But I can't Post a Request to the server, it always gets the following error :
Error Domain=AFNetworkingErrorDomain Code=-1011 "Request failed: forbidden (403)" UserInfo=0x79eb1330 {NSErrorFailingURLKey=https://api.instagram.com/.../950394368622277294.../likes, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0x7a12c8c0> { URL: https://api.instagram.com/.../950394368622277294.../likes } { status code: 403, headers {
"Cache-Control" = "private, no-cache, no-store, must-revalidate";
Connection = "keep-alive";
"Content-Language" = en;
"Content-Length" = 143;
"Content-Type" = "application/json";
Date = "Sat, 28 Mar 2015 10:07:53 GMT";
Expires = "Sat, 01 Jan 2000 00:00:00 GMT";
Pragma = "no-cache";
Server = nginx;
Vary = "Accept-Language, Cookie";
"X-Instagram-Ssl-Wifi" = False;
} }, NSLocalizedDescription=Request failed: forbidden (403)}
when calling this method:
- (void)postPath:(NSString *)path
parameters:(NSDictionary *)parameters
responseModel:(Class)modelClass
success:(void (^)(NSDictionary *responseObject))success
failure:(void (^)(NSError* error, NSInteger statusCode))failure
{
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:parameters];
if (self.accessToken) {
// NSString *p = [NSString stringWithFormat:#"access_token=%#", self.accessToken];
NSString *percentageEscapedPath = [self.accessToken stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[params setObject:percentageEscapedPath forKey:kKeyAccessToken];
// [params setObject:self.appClientID forKey:kKeyClientID];
}
else
[params setObject:self.appClientID forKey:kKeyClientID];
[self.httpManager POST:path
parameters:params
#if (__IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0)
success:^(AFHTTPRequestOperation *operation, id responseObject) {
#else
success:^(NSURLSessionDataTask *task, id responseObject) {
#endif
NSDictionary *responseDictionary = (NSDictionary *)responseObject;
success(responseDictionary);
}
#if (__IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0)
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
failure(error,[[operation response] statusCode]);
#else
failure:^(NSURLSessionDataTask *task, NSError *error) {
failure(error,((NSHTTPURLResponse*)[task response]).statusCode);
#endif
}];
}
I am having problems in saving a response coming from a POST request.
Based on AFnetworking documentation and NSScreencast tutorial I created my own subclass of AFHTTPRequestOperationManager, but I am not sure why the response is not saved.
How do I know, the response is not saved?
Because there is an error:(null) message in console and the my method does not perform segue.
I know that I am getting the values, because of the breakpoint that I put NSURLSessionDataTask
But I do not know why the values are not saved and I am getting an error message. I appreciate any help.
The APIClient/Manager
AuthAPIManager.h
#import "AFHTTPSessionManager.h"
#interface AuthAPIManager : AFHTTPSessionManager
+(AuthAPIManager *)sharedManager;
-(NSURLSessionDataTask *)initializeLogin:(NSString *)username completion:(void(^)(NSDictionary *results, NSError *error))completion;
//for login
#property (nonatomic,readonly,retain)NSString *StoreIdentifierForVendor;
#property(nonatomic,copy)NSString *devicetype;
#end
AuthAPIManager.m
#import "AuthAPIManager.h"
#import "LoginInfo.h"
#import "CredentialStore.h"
static AuthAPIManager *sharedManager =nil;
static dispatch_once_t onceToken;
#implementation AuthAPIManager
+(AuthAPIManager *)sharedManager
{
dispatch_once(&onceToken, ^{
sharedManager = [[AuthAPIManager alloc] initWithBaseURL:[NSURL URLWithString:BASE_URL]];
sharedManager.responseSerializer=[AFJSONResponseSerializer serializer];
sharedManager.requestSerializer = [AFJSONRequestSerializer serializer];
});
return sharedManager;
}
-(id)initWithBaseURL:(NSURL *)url
{
self = [super initWithBaseURL:url];
if (self) {
}
return self;
}
-(NSURLSessionDataTask *)initializeLogin:(NSString *)username completion:(void (^)(NSDictionary *, NSError *))completion
{
_devicetype = #"ios";
_StoreIdentifierForVendor = [[[UIDevice currentDevice]identifierForVendor]UUIDString];
id loginParameters =#{#"AccountId":username,
#"DeviceType":_devicetype
};
NSURLSessionDataTask *task =[self POST:#"/Accn" parameters:loginParameters
success:^(NSURLSessionDataTask *task, id responseObject)
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)task.response;
if (httpResponse.statusCode == 200) {
LoginInfo *loginInfo =[[LoginInfo alloc]initWithDictionary:responseObject];
CredentialStore *credStore =[CredentialStore sharedStore];
credStore.loginInfo =loginInfo;
completion(responseObject,nil);
loginInfo = responseObject;
} else {
dispatch_async(dispatch_get_main_queue(), ^{
completion(nil, nil);
});
NSLog(#"Received: %#", responseObject);
NSLog(#"Received HTTP %d", httpResponse.statusCode);
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(nil, error);
});
}];
return task;
}
#end
And this is how I am calling my method in my view controller
- (IBAction)login:(id)sender
{
[_usernameTextField resignFirstResponder];
[SVProgressHUD show];
NSURLSessionDataTask *task = [[AuthAPIManager sharedManager] initializeLogin:self.usernameTextField.text completion:^(NSDictionary *results, NSError *error)
{
if (results) {
LoginInfo *loginInfo = [[LoginInfo alloc]initWithDictionary:results];
CredentialStore *credStore =[ CredentialStore sharedStore];
credStore.loginInfo =loginInfo;
[self performSegueWithIdentifier:#"welcomeViewSegue" sender:self];
}
else
{
NSLog(#"there is an error:%#",error);
}
}];
[SVProgressHUD dismiss];
}
Your success block is being called, but your status code is not 200.
You are calling your completion block like this:
completion(nil, nil);
So this code:
if (results) {
[snip]
}
else
{
NSLog(#"there is an error:%#",error);
}
is passed a nil results object.
Set a breakpoint on if (httpResponse.statusCode == 200) and inspect httpResponse in your debugger to see why it's not what you expect. (You may get a different success code, such as 204.)
Call your completion block with results instead of nil.