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
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.
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 trying to call a POST API on Instagram using AFNetworking, and my code to call is:
void (^mySuccessBlock)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary* userInfo = (NSDictionary*) responseObject;
if (block != nil) {
block(userInfo, nil);
}
};
void (^failureBlock)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Request Error: %#", error);
if (block != nil) {
block(nil, error);
}
};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *param=[[NSMutableDictionary alloc]init];
NSString * token =[defaults objectForKey:ACCESS_TOKEN];
[param setValue:token forKey:#"access_token"];
NSString *url=[NSString stringWithFormat:#"https://api.instagram.com/v1/media/%#/likes" , globalMediaId];
[manager POST:url parameters:param success:mySuccessBlock failure:failureBlock ];
But I am getting this error:
request Error: Error Domain=com.alamofire.error.serialization.response
Code=-1011 "Request failed: bad request (400)" UserInfo=0x7fb4c9698e00
{com.alamofire.serialization.response.error.response= { URL:
https://api.instagram.com/v1/media/853150485752748330_1509614005/likes
} { status code: 400, headers {
"Cache-Control" = "private, no-cache, no-store, must-revalidate";
Connection = "keep-alive";
"Content-Language" = en;
"Content-Length" = 114;
"Content-Type" = "application/json; charset=utf-8";
Date = "Mon, 29 Jun 2015 05:55:33 GMT";
Expires = "Sat, 01 Jan 2000 00:00:00 GMT";
Pragma = "no-cache";
"Set-Cookie" = "csrftoken=f4b5426f69b154c60e6785ba52100a09; expires=Mon, 27-Jun-2016 05:55:33 GMT; Max-Age=31449600; Path=/";
Vary = "Cookie, Accept-Language"; } }, NSErrorFailingURLKey=https://api.instagram.com/v1/media/853150485752748330_1509614005/likes,
com.alamofire.serialization.response.error.data=<7b226d65 7461223a
7b226572 726f725f 74797065 223a224f 41757468 50617261 6d657465
72457863 65707469 6f6e222c 22636f64 65223a34 30302c22 6572726f
725f6d65 73736167 65223a22 4d697373 696e6720 61636365 73735f74
6f6b656e 2055524c 20706172 616d6574 65722e22 7d7d>,
NSLocalizedDescription=Request failed: bad request (400)}
Does anyone know why I'm getting this?
I tried lots but getting this error while calling this api for getting match schedule using this
- (IBAction)getButtonPressed:(id)sender
{
NSString *string = [NSString stringWithFormat:#"https://api.sportsdatallc.org/nba-Trial(t)1/ru/games/2014/reg/schedule.json?api_key=qgdmf6egtuf5guy9pdvk5ydf"];
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSLog(#"url is %#",url);
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// 3
NSLog(#"%#",responseObject);
} 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];
}];
// 5
[operation start];
}
getting this error
Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: server error (596)" UserInfo=0x7994db10 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x799335b0> { URL: https://api.sportsdatallc.org/nba-Trial(t)1/ru/games/2014/reg/schedule.json?api_key=qgdmf6egtuf5guy9pdvk5ydf } { status code: 596, headers {
Connection = "keep-alive";
"Content-Length" = 30;
"Content-Type" = "text/xml";
Date = "Fri, 20 Mar 2015 08:55:01 GMT";
Server = "Mashery Proxy";
"X-Mashery-Error-Code" = "ERR_596_SERVICE_NOT_FOUND";
} }, NSErrorFailingURLKey=https://api.sportsdatallc.org/nba- Trial(t)1/ru/games/2014/reg/schedule.json?api_key=qgdmf6egtuf5guy9pdvk5ydf, NSLocalizedDescription=Request failed: server error (596), com.alamofire.serialization.response.error.data=<3c68313e 35393620 53657276 69636520 4e6f7420 466f756e 643c2f68 313e>, NSUnderlyingError=0x7994eb90 "Request failed: unacceptable content-type: text/xml"}
I am using this website api:
http://developer.sportsdatallc.com/docs/NBA_API
Details of using this api:
Daily Schedule
Schema
Syntax:
http(s)://api.sportsdatallc.org/nba-[access_level][version]/schema/schedule-v2.0.xsd?api_key=[your_api_key]
Schema Example:
Feed
Syntax:
http(s)://api.sportsdatallc.org/nba-[access_level][version]/[locale]/games/[year]/[month]/[day]/schedule.xml?api_key=[your_api_key]
Parameter Format Notes
[access_level] = Production (p), Trial (t)
[version] = whole number (sequential, starting with the number 1)
[year] = Year in 4 digit format (YYYY)
[month] = Month in 2 digit format (MM)
[day] = Day of the month in 2 digit format (DD)
[format] = xml, json
Optional Parameters
[locale] = ru (russian), zh (simplified chinese)
In -[AFHTTPRequestOperationManager initWithBaseURL:], you will find that the responseSerializer property is set to an instance of AFJSONResponseSerializer. .
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:myURL];
To get the functionality you want(delivering a parsed XML model back to your callback as the responseObject), simply set the responseSerializer property to an instance of AFXMLResponseSerializer
manager.responseSerializer = [AFXMLResponseSerializer new];
Sample Code:
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:myURL];
manager.responseSerializer = [AFXMLResponseSerializer new];
[manager GET:#"http://www.example.com/feed" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Data: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
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.