How to pass array value using AFNetworking? - ios

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.

Related

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?

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

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.

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.

iOS Youtube API v3 Subscribe to a youtube channel

I'm using Youtube API v3.0 in an iPhone app, and I have already handled youtube authorization using Google plus API. Now I need to subscribe to a youtube channel following the example here in the link..
https://developers.google.com/youtube/v3/docs/subscriptions/insert#examples
So in my code..
NSString *URLString = [NSString stringWithFormat:#"https://www.googleapis.com/youtube/v3/subscriptions?part=snippet&key=%#", API_KEY];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
[requestSerializer setValue:[AOTube accessToken] forHTTPHeaderField:#"Authorization"];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
manager.requestSerializer = requestSerializer;
NSDictionary *parameters = #{#"snippet":#{
#"resourceId":#{
#"channelId":CHANNEL_ID,
#"kind":#"youtube#channel"
}
}
};
[manager POST:URLString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
success(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
failure(error);
}];
I got the following error from the failure block..
Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: unauthorized (401)" UserInfo=0x7f8983d5cab0 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x7f8983d40ca0> { URL: https://www.googleapis.com/youtube/v3/subscriptions?part=snippet&key=AIzaSyB1mipmXC8dmXduIJXJ7qt9CxmLlnuc8aw } { status code: 401, headers {
"Cache-Control" = "private, max-age=0";
"Content-Encoding" = gzip;
"Content-Length" = 162;
"Content-Type" = "application/json; charset=UTF-8";
Date = "Sun, 04 Jan 2015 22:00:55 GMT";
Expires = "Sun, 04 Jan 2015 22:00:55 GMT";
Server = GSE;
Vary = "Origin, X-Origin";
"Www-Authenticate" = "Bearer realm=\"https://accounts.google.com/AuthSubRequest\"";
"alternate-protocol" = "443:quic,p=0.02";
"x-content-type-options" = nosniff;
"x-frame-options" = SAMEORIGIN;
"x-xss-protection" = "1; mode=block";
} }, NSErrorFailingURLKey=https://www.googleapis.com/youtube/v3/subscriptions?part=snippet&key=ewrqDSyB1sfrgdmXduIJfwrgrwgLlnuc8aw, com.alamofire.serialization.response.error.data=<7b0a2022 6572726f 72223a20 7b0a2020 22657272 6f727322 3a205b0a 2020207b 0a202020 2022646f 6d61696e 223a2022 676c6f62 616c222c 0a202020 20227265 61736f6e 223a2022 61757468 4572726f 72222c0a 20202020 226d6573 73616765 223a2022 496e7661 6c696420 43726564 656e7469 616c7322 2c0a2020 2020226c 6f636174 696f6e54 79706522 3a202268 65616465 72222c0a 20202020 226c6f63 6174696f 6e223a20 22417574 686f7269 7a617469 6f6e220a 2020207d 0a20205d 2c0a2020 22636f64 65223a20 3430312c 0a202022 6d657373 61676522 3a202249 6e76616c 69642043 72656465 6e746961 6c73220a 207d0a7d 0a>, NSLocalizedDescription=Request failed: unauthorized (401)}
I'm sure that there's nothing wrong about API_KEY, CHANNEL_ID, and the access token since I'm already using them in other web services successfully
You don't have correct to set authorization header field.
Instead of:
[requestSerializer setValue:[AOTube accessToken] forHTTPHeaderField:#"Authorization"];
use:
NSString *authValue = [NSString stringWithFormat:#"Bearer %#", [AOTube accessToken]];
[requestSerializer setValue: authValue forHTTPHeaderField:#"Authorization"];
Next correct your request serializer to:
AFHTTPRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
In authorization process add at least one of the following scopes: https://www.googleapis.com/auth/youtubepartner or https://www.googleapis.com/auth/youtube
sample:
signIn.scopes = #[ kGTLAuthScopePlusLogin, #"https://www.googleapis.com/auth/youtube" ];
If you are proper signed using Google API you don't must include API key request parameter in URL.

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. 😊👍

Resources