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.
Related
I'm pretty new to Xcode, and I'm trying to make a POST request. I searched on Google and found this AFNetworking library. I've read some documentation but they all say different things. So now I use their own example on a POST request and my code looks like this:
- (void)viewDidLoad {
[super viewDidLoad];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"fName": #"firstname", #"lName": #"lastname"};
[manager POST:#"http://00000.1111.ovh/api/Account/register" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
And then I get this error:
Error: Error Domain=com.alamofire.error.serialization.response
Code=-1011 "Request failed: bad request (400)"
UserInfo={com.alamofire.serialization.response.error.response= { URL: http://00000.1111.ovh/api/Account/register } {
status code: 400, headers {
"Content-Length" = 159;
"Content-Type" = "application/json; charset=utf-8";
Date = "Sun, 15 Nov 2015 12:11:57 GMT";
Server = "Microsoft-IIS/8.5";
"X-Powered-By" = "ASP.NET"; } }, NSErrorFailingURLKey=http://00000.1111.ovh/api/Account/register,
com.alamofire.serialization.response.error.data=<7b226d65 73736167
65223a22 54686520 72657175 65737420 69732069 6e76616c 69642e22
2c226d6f 64656c53 74617465 223a7b22 6c6f6769 6e2e7573 65726e61
6d65223a 5b225468 65205573 6572206e 616d6520 6669656c 64206973
20726571 75697265 642e225d 2c226c6f 67696e2e 70617373 776f7264
223a5b22 54686520 50617373 776f7264 20666965 6c642069 73207265
71756972 65642e22 5d7d7d>, NSLocalizedDescription=Request failed: bad
request (400)}
Hope someone can help me!
You can better diagnose these issues if you translate the server's response into something you can parse/examine:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"fName": #"firstname", #"lName": #"lastname"};
[manager POST:#"http://00000.1111.ovh/api/Account/register" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON = %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error = %#", error);
if (operation.responseObject) {
NSLog(#"responseObject = %#", operation.responseObject);
} else {
NSLog(#"responseString = %#", operation.responseString);
}
}];
If you did that, you'd see that it responded with:
responseObject = {
message = "The request is invalid.";
modelState = {
"login.password" = (
"The Password field is required."
);
"login.username" = (
"The User name field is required."
);
};
}
Apparently, the request was missing the necessary authentication details.
Your request is sent correctly, but the server responded with HTTP code 400. Check the server's API documentation on how the request should look like.
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 wanted to get data from server encoded in json to display it, so i use afnetworking library but i get error here is my code
NSURL * url =[NSURL URLWithString:#"http://software-sultan.com/alaa/image_test.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// 3
array = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
NSLog(#"%#",error);
}];
// 5
[operation start];
here is the error
Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo=0x7f920964bff0 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x7f920965cc20> { URL: http://software-sultan.com/alaa/image_test.php } { status code: 200, headers {
Connection = "keep-alive";
"Content-Length" = 126781;
"Content-Type" = "text/html";
Date = "Thu, 29 Jan 2015 19:00:55 GMT";
"Keep-Alive" = "timeout=30";
Server = "Apache/2";
"X-Powered-By" = "PHP/5.3.13";
} }, NSErrorFailingURLKey=http://software-sultan.
It looks like you are trying to parse a JSON response with AFJSONResponseSerializer, but the webserver sends text/html as content type. JSON responses are generally served with the Content-Type: application/json header.
Also, if the response was successfully parsed as JSON, the responseObject given as the second parameter of your completion block would already be a valid NSArray containing your data. So there wouldn't need to create it again using NSJSONSerialization.