How to use AFNetwowrking2.0 code for this Example url? - ios

Hi I have one example url Which returns JSON Format. but when i use AFNetWorking2.0 to get the response from that URL, i am not getting correct Response. Here i am sending my code also.
- (void)testHTTPS {
AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
[securityPolicy setAllowInvalidCertificates:YES];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager setSecurityPolicy:securityPolicy];
[manager GET:#"xxxxx"
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
NSString* newStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
I am getting JSON Dic always nil. and if i print "newstr" i am getting html format response. can anyone please find correct way?
I have done as you said John but i am getting the below result
Error: Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo=0x7ffb39c52ed0 {com.alamofire.serialization.response.error.response= { URL: xxxxx } { status code: 200, headers {
"Cache-Control" = "public, max-age=10800";
"Content-Encoding" = gzip;
"Content-Length" = 2922;
"Content-Type" = "text/html";
Date = "Wed, 29 Apr 2015 06:49:54 GMT";
Expires = "Wed, 29 Apr 2015 09:49:55 GMT";
"Last-Modified" = "Wed, 01 Apr 2015 03:19:39 GMT";
Server = "ECAcc (hhp/9ABE)";
Vary = "Accept-Encoding";
"X-Cache" = HIT;
} }, NSErrorFailingURLKey=xxxxx, com.alamofire.serialization.response.error.data=<0d0a3c21 444f4354 59504520 68746d6c 20505542 4c494320 222d2f2f 5733432f 2f445444 20584854 4d4c2031 2e302054 72616e73 6974696f 6e616c2f 2f454e22 20226874 74703a2f 2f777777 2e77332e 6f72672f 54522f78 68746d6c 312f4454 442f7868 746d6c31 2d747261 6e736974 696f6e61 6c2e6474 64223e0d 0a3c6874 6d6c2078 6d6c6e73 3d226874 74703a2f 2f777777 2e77332e 6f72672f 31393939 2f786874 6d6c223e 0d0a3c68 6561643e 0d0a3c6d 65746120 68747470 2d657175 69763d22 436f6e74 656e742d 54797065 2220636f 6e74656e >, NSLocalizedDescription=Request failed: unacceptable content-type: text/html}

The problem is that you're using the AFHTTPResponseSerializer rather than AFNetworking's AFJSONResponseSerializer. Therefore, when the response comes in, it is parsing it as a HTTP response rather than a JSON response. This is easily fixed by assigning your manager.responseSerializer to AFJSONResponseSerializer instead:
manager.responseSerializer = [AFJSONResponseSerializer serializer];
You'll find that you won't need to create an NSDictionary from the response - upon success it should come through as an NSDictionary object already.
Check out the AFNetworking 2.0 migration guide. It's a very handy read and will make you aware of what to look out for in the future.

Related

How to pass array value using AFNetworking?

Now i am working in paypal recurring integration using APIS, i am facing request format problem in the following API.
How to send request format as same as fellow.
curl -v -k -X PATCH 'https://api.sandbox.paypal.com/v1/payments/billing-plans/P-94458432VR012762KRWBZEUA' \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <Access-Token>" \
-d '[
{
"path": "/",
"value": {
"state": "ACTIVE"
},
"op": "replace"
}
]'
So far i have tried following code
NSDictionary *valueDic = #{#"state":#"ACTIVE"};
NSDictionary *parametersDic = #{#"path":#"/",#"value":valueDic,#"op":#"replace"};
NSMutableArray *parameterArray = [[NSMutableArray alloc] init];
[parameterArray addObject:parametersDic];
NSString *finalyToken = [[NSString alloc]initWithFormat:#"Bearer %#",strAccessToken];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager.requestSerializer setValue:finalyToken forHTTPHeaderField:#"Authorization"];
[manager.requestSerializer setValue:#"application/json+patch" forHTTPHeaderField:#"Content-Type"];
[manager.responseSerializer.acceptableContentTypes setByAddingObject:#"application/json"];
NSString *urlPatch = [NSString stringWithFormat:#"https://api.sandbox.paypal.com/v1/payments/billing-plans/%#",creditCardId];
[manager PATCH:urlPatch parameters:parameterArray success:^(AFHTTPRequestOperation *operation, id responseObject){
NSLog(#"JSON: %#", responseObject);
[self recurringCreateBillingAgreement];
}failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
i have created request format like above
(
{
op = replace;
path = "/";
value = {
state = ACTIVE;
};
}
)
But,I am getting following error
Error: Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: internal server error (500)" UserInfo=0x177155d0 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x1755c9b0> { URL: https://api.sandbox.paypal.com/v1/payments/billing-plans/P-1DT55351E261652436BZHSLA } { status code: 500, headers {
"CORRELATION-ID" = 6bf7cbf78bb16;
Connection = "close, close";
"Content-Length" = 196;
"Content-Type" = "text/xml;charset=UTF-8";
Date = "Thu, 07 Apr 2016 11:19:08 GMT";
"PROXY_SERVER_INFO" = "host=slcsbplatformapiserv3001.slc.paypal.com;threadId=368";
"Paypal-Debug-Id" = "6bf7cbf78bb16, 6bf7cbf78bb16";
Server = Apache;
"Set-Cookie" = "X-PP-SILOVER=name%3DSANDBOX3.API.1%26silo_version%3D1880%26app%3Dplatformapiserv%26TIME%3D742524503; domain=.paypal.com; path=/; Secure; HttpOnly, X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT";
Vary = Authorization;
} }, NSErrorFailingURLKey=https://api.sandbox.paypal.com/v1/payments/billing-plans/P-1DT55351E261652436BZHSLA, NSLocalizedDescription=Request failed: internal server error (500), com.alamofire.serialization.response.error.data=<3c6e7331 3a584d4c 4661756c 7420786d 6c6e733a 6e73313d 22687474 703a2f2f 6378662e 61706163 68652e6f 72672f62 696e6469 6e67732f 78666f72 6d617422 3e3c6e73 313a6661 756c7473 7472696e 6720786d 6c6e733a 6e73313d 22687474 703a2f2f 6378662e 61706163 68652e6f 72672f62 696e6469 6e67732f 78666f72 6d617422 3e6a6176 612e6c61 6e672e4e 756c6c50 6f696e74 65724578 63657074 696f6e3c 2f6e7331 3a666175 6c747374 72696e67 3e3c2f6e 73313a58 4d4c4661 756c743e>, NSUnderlyingError=0x1757d4c0 "Request failed: unacceptable content-type: text/xml"}
You need to send JSON string as one parameter.
You can create JSON string of your array as below.
NSData *data = [NSJSONSerialization dataWithJSONObject:parameterArray options:0 error:nil];
NSString* jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
parameterArray will be your array
Now use jsonString as value of one of your parameters, so you can send it to server.

Getting Error when using AFNetwork to call a post API

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?

Request failed: unacceptable content-type: application/osm3s+xml

I'm trying to send request to OpenStreetMap api, and I'm still failing to do so. Please help me out what's incorrect.
My method:
NSString *url = #"http://api.openstreetmap.fr/xapi?node[name=London]";
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/osm3s+xml"];
[manager setResponseSerializer:[AFXMLParserResponseSerializer new]];
[manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, NSData *responseObject) {
NSLog(#"DATA: %#", responseObject);
[self stopProgress];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
self.textView.text = error.description;
[self stopProgress];
}];
Error:
Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: application/osm3s+xml" UserInfo=0x1702e1e80 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x17403d080> { URL: http://api.openstreetmap.fr/xapi?node%5Bname=London%5D } { status code: 200, headers {
Connection = "Keep-Alive";
"Content-Encoding" = gzip;
"Content-Length" = 7166;
"Content-Type" = "application/osm3s+xml";
Date = "Sun, 25 Jan 2015 21:18:54 GMT";
"Keep-Alive" = "timeout=5, max=100";
Server = "Apache/2.2.22 (Debian)";
Vary = "Accept-Encoding";
} }, NSErrorFailingURLKey=http://api.openstreetmap.fr/xapi?node%5Bname=London%5D, com.alamofire.serialization.response.error.data=<3c3f786d 6c207665 7273696f 6e3d2231 2e302220 656e636f 64696e67 (... a lot of numbers ... )>, NSLocalizedDescription=Request failed: unacceptable content-type: application/osm3s+xml}
Your code:
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/osm3s+xml"];
Very clearly creates the header that OpenStreetMap is rejecting. Don't set that header: set it to a value like text/xml, which is documented as the right value.

AFnetworking keep returning response Code=-1011 "Request failed: client error (422)

I'm try to use AFNetworking to create a POST request. However I always return an error says:
Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: client error (422)" UserInfo=0x7ff1fa76a5c0 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x7ff1fa76ce40> { URL: https://isisfriends.zendesk.com/requests/mobile_api/create.json } { status code: 422, headers {
"Cache-Control" = "no-cache";
Connection = "keep-alive";
"Content-Length" = 33;
"Content-Type" = "application/json; charset=UTF-8";
Date = "Mon, 20 Oct 2014 14:56:54 GMT";
P3P = "CP=\"NOI DSP COR NID ADMa OPTa OUR NOR\"";
Server = nginx;
"Set-Cookie" = "_zendesk_shared_session=eyJpZCI6IjUxYjdmOGFjMzZjMzE1MjRjNDE0OTFiMjRmYmYzNjhhIiwibG9jYWxlX2lkIjoxfQ%3D%3D--229c90ddd7cf33dc5886aba445fd51cccaf69ea7; path=/; secure; HttpOnly, _zendesk_session=BAh7CkkiD3Nlc3Npb25faWQGOgZFVEkiJWVhZTRmZTQ5ZDQ1NmZjOTgzZDBlMzgyMWQ5YjMwMjNlBjsAVEkiDGFjY291bnQGOwBGaQMdNgdJIgpyb3V0ZQY7AEZpAuq9SSIOaXNfbW9iaWxlBjsAVFRJIhN3YXJkZW4ubWVzc2FnZQY7AFR7AA%3D%3D--c8bf5a2774eb5fdaa8ff7ec2da6adef3f76b15c3; path=/; secure; HttpOnly";
Status = "422 Unprocessable Entity";
Vary = Accept;
"X-Frame-Options" = SAMEORIGIN;
"X-Rack-Cache" = "invalidate, pass";
"X-Request-Id" = b71fc58dc1cf122d395b77968aff9014;
"X-Runtime" = "0.088859";
"X-UA-Compatible" = "IE=Edge,chrome=1";
"X-XSS-Protection" = "1; mode=block";
"X-Zendesk-Origin-Server" = "app13.pod2.sac1.zdsys.com";
"X-Zendesk-Request-Id" = 10c9143fd5ac87ab66d3;
} }, NSErrorFailingURLKey=https://isisfriends.zendesk.com/requests/mobile_api/create.json, com.alamofire.serialization.response.error.data=<7b226572 726f7222 3a22496e 76616c69 6420656d 61696c20 61646472 65737322 7d>, NSLocalizedDescription=Request failed: client error (422)}
Here is my code:
NSString * question = [_textFieldQuestion text];
NSString * detail = [_textFieldDetails text];
NSString * email = [_textFieldEmail text];
if(question.length > 0 && detail.length > 0 && email.length > 0)
{
NSString *url = #"https://isisfriends.zendesk.com/requests/mobile_api/create.json";
NSDictionary *parameters = #{#"subject":question, #"description":detail, #"email":email};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFJSONRequestSerializer *reqSerializer = [AFJSONRequestSerializer serializer];
[reqSerializer setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[reqSerializer setValue:#"1.0" forHTTPHeaderField:#"X-Zendesk-Mobile-API"];
manager.requestSerializer = reqSerializer;
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSLog(parameters.descriptionInStringsFileFormat);
[manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"===== JSON: ======= %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"============== Error: ============\n%#", [error description]);
}];
} else {
}
I'm petty sure the parameters I provided (subject, description, email)is corrent, becuase if I put the parameters directly in the url like below, it works fine.
https://isisfriends.zendesk.com/requests/mobile_api/create.json?subject=testing&email=testing#asd.com&description=testing
422 client error is for failed authentication. Check if you need any authentication or if you think You have permission, Look for the logged Failure error serialised in the console to check what server has to say about your call.
Use this simplified code:
NSString *myUrlString= YOUR LINK;
NSMutableDictionary* postRequestDictionary = [[NSMutableDictionary alloc] init];
postRequestDictionary[#"YOUR PARAMATER"]= YOUR PARAMETER VALUE;
// ... ADD ANY MORE PARAMETER IF YOU WANT HERE ...
NSLog(#"body = %#",postRequestDictionary);
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc]init];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:#"HEADER VALUE" forHTTPHeaderField:#"HEADER"];
// ... ADD ANYMORE HEADER IF YOU WANT ...
[manager POST:myUrlString parameters:postRequestDictionary success:^(AFHTTPRequestOperation *requestOperation,id JSON){
NSLog(#"%#",JSON);
} failure:^(AFHTTPRequestOperation *requestFailureOperation , NSError *error){
NSLog(#"%#",error);
NSData *errorData = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey];
NSDictionary *serializedData = [NSJSONSerialization JSONObjectWithData: errorData options:kNilOptions error:nil];
NSLog(#"Failure error serialised - %#",serializedData);
}];
Hope this helps. 😊👍

AFNetworking getting json value. URL doesn't work

Im using AFNetworking to get JSON values from my iOS application i have tested my code to this link http://gdata.youtube.com/feeds/api/standardfeeds/most_popular?v=2&alt=json then my code works fine. but when i use http://www.fr20.wearedesigners.net/WADMac/tourism/fetchGuideListAndroid.php this link to retrieve data im getting following Error please find below the code i used.please help me to retrieve data from my URL
-(void) retriveData
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setValue:#"text/html" forHTTPHeaderField:#"Content-type"];
[manager GET:#"http://www.fr20.wearedesigners.net/WADMac/tourism/fetchGuideListAndroid.php" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
Error log
2014-07-19 18:36:01.107 WADTourisum[3000:60b] Reachability Flag Status: -R ------- networkStatusForFlags
2014-07-19 18:36:01.768 WADTourisum[3000:60b] Error: Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo=0xa05c4e0 {NSErrorFailingURLKey=http://www.fr20.wearedesigners.net/WADMac/tourism/fetchGuideListAndroid.php, com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x8d8ba40> { URL: http://www.fr20.wearedesigners.net/WADMac/tourism/fetchGuideListAndroid.php } { status code: 200, headers {
Connection = "Keep-Alive";
"Content-Type" = "text/html";
Date = "Sat, 19 Jul 2014 13:05:32 GMT";
"Keep-Alive" = "timeout=5, max=100";
Server = "Apache/2.2.19 (Unix) mod_ssl/2.2.19 OpenSSL/0.9.8e-fips-rhel5 DAV/2 mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635";
"Transfer-Encoding" = Identity;
"X-Powered-By" = "PHP/5.2.17";
} }, NSLocalizedDescription=Request failed: unacceptable content-type: text/html}
it happens
NSLocalizedDescription=Request failed: unacceptable content-type: text/html
format Content-Type" = "text/html doesn't have your AFNetworking.
Simply go to Serilization->AFURLResponseSerialization.m, line 215, and change it:
self.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript",#"text/html", nil];
it will work you.
More recent versions may have the code on line 223.
Solution for Swift:
It will accept most of the content type.
let manager=AFHTTPRequestOperationManager()
manager.responseSerializer = AFJSONResponseSerializer(readingOptions: NSJSONReadingOptions.AllowFragments) as AFJSONResponseSerializer
manager.requestSerializer = AFJSONRequestSerializer() as AFJSONRequestSerializer
manager.responseSerializer.acceptableContentTypes = NSSet(objects:"application/json", "text/html", "text/plain", "text/json", "text/javascript", "audio/wav") as Set<NSObject>
The url you use (http://www.fr20.wearedesigners.net/WADMac/tourism/fetchGuideListAndroid.php ) returns a not accepted content-type header, instead of text/html it should return application/json.
As Otanaught says, the url you use (http://www.fr20.wearedesigners.net/WADMac/tourism/fetchGuideListAndroid.php ) returns a not accepted content-type header, instead of text/html it should return application/json.
If you have access to the PHP Web Service file, put this before any display code:
header('Content-type: application/json');
If u r using afnetwork 2.6.3 then
Simply go to Serilization -> AFURLResponseSerialization.m, line 224, and change it to:
self.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript",#"text/html", nil];
it will work you.

Resources