I'm trying to make a function that I'll call to handle the AFNetworking JSON parse.
Here is my code:
- (int)startParseWithParameters:(NSDictionary*)incomingParameters andUrlAdress:(NSString*)urlAdress;
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSDictionary *parameters = incomingParameters;
[manager POST:urlAdress parameters:parameters success:^
(AFHTTPRequestOperation *operation, id responseObject)
{
NSString *recivedErr = responseObject[#"error"];
_errValue = [recivedErr intValue];
NSLog(#"JSON: %d", _errValue);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error: %#", error);
}];
return _errValue;
}
I want the function to return 0 or 1, then I'll know if there is an error or not.
Right now it always return 0.
When I try to return in the success block I get a compiler error.
What could cause this problem?
The succes block is handled async so you should just call a method in the block:
- (void)startParseWithParameters:(NSDictionary*)incomingParameters andUrlAdress:(NSString*)urlAdress {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSDictionary *parameters = incomingParameters;
__weak typeof(self) weakSelf = self;
[manager POST:urlAdress parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *recivedErr = responseObject[#"error"];
[weakSelf didReceiveResponse:[recivedErr integerValue];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
-(void)didReceiveResponse:(NSInteger)status {
}
Related
I'm currently learning blocks, and I want to use them with AFNetworking. I made method in Singletone:
- (void)getAllPlayers:(void (^)(NSArray *playerz, bool succeed))blockPlayers {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:#"https://api.myjson.com/bins/530re" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
I called this method in viewDidLoad:
[[Manager sharedInstance]getAllPlayers:^(NSArray *playerz, bool succeed) {
if (succeed == YES) {
self.allClubs = playerz;
[self.tableView reloadData];
}
}];
But nothing is downloaded.
Yo forgot to call the blockPlayers Completion handler.
- (void)getAllPlayers:(void (^)(NSArray *playerz, bool succeed))blockPlayers {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:#"https://api.myjson.com/bins/530re" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSarray *returnedPLayerz = [NSArray array];
//Here treat operation and response Object to extract playerz and assing it to returnedPlayerz
blockPLayers(returnedPlayerz, YES);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
blockPlayers(nil, NO);
NSLog(#"Error: %#", error);
}];
}
You got data from server in response object. After that you need to parse it and return in block:
- (void)getAllPlayers:(void (^)(NSArray *playerz, bool succeed))blockPlayers {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:#"https://api.myjson.com/bins/530re" parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSArray* players = [self getPlayersFromJson:responseObject];
blockPlayers(players, YES);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
blockPlayers(nil, NO);
}];
}
So you need to create parser method getPlayersFromJson
AFNetworking response failure block is being called when I get status code 200. How can I make the success be called instead?
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:#"http://128.199.94.58/test/bt/client_token.php" parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.clientToken = responseObject[#"customerID"];
NSLog(#"Client Token received.");
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// Handle failure communicating with your server
NSLog(#"Client Token request failed.%#",operation.responseString);
NSLog(#"error code %ld",(long)[operation.response statusCode]);
}];
Look at the value of error. It will tell you why the connection failed. "Failure" in this context has nothing to do with the status code. Returning "404" is still a "success." Failure means you were unable to complete the operation.
use acceptableStatusCodes as follows:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [TimeoutAFJSONRequestSerializer serializer];
NSMutableIndexSet* codes = [[NSMutableIndexSet alloc] init];
[codes addIndex: 200];
manager.responseSerializer.acceptableStatusCodes = codes;
[manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
{
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
}];
I run this code and it work find.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:#"http://128.199.94.58/test/bt/client_token.php" parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseObject
options:kNilOptions
error:nil];
self.clientToken = json[#"customerID"];
NSLog(#"Client Token received.");
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// Handle failure communicating with your server
NSLog(#"Client Token request failed.%#",operation.responseString);
NSLog(#"error code %ld",(long)[operation.response statusCode]);
}];
responce is:
json:
{
customerID = "eyJ2ZXJzaW9uIjoyLCJhdXRob3JpemF0aW9uRmluZ2VycHJpbnQiOiJhMjg2OGVjY2FmZjNjMTQ0M2Y4MTg2MjQ4NDFhZDIyZGM3MWFhOTQ0MmFiMTY2NWVlNWY1YjJkODdiOTVhYzBjfGNyZWF0ZWRfYXQ9MjAxNS0wNS0xNFQxMzoyMDowNi45NjE2NDQxNzArMDAwMFx1MDAyNm1lcmNoYW50X2lkPXpxZDlkcGpmZmRzazd4bnlcdTAwMjZwdWJsaWNfa2V5PWRoeTdqeGt6Z3Y4d3dkcGoiLCJjb25maWdVcmwiOiJodHRwczovL2FwaS5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tOjQ0My9tZXJjaGFudHMvenFkOWRwamZmZHNrN3hueS9jbGllbnRfYXBpL3YxL2NvbmZpZ3VyYXRpb24iLCJjaGFsbGVuZ2VzIjpbImN2diJdLCJlbnZpcm9ubWVudCI6InNhbmRib3giLCJjbGllbnRBcGlVcm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mVubW8iOiJvZmYifQ==";
}
It may be work for you.
If you check your error in failure block it clearly say that invalid content type. You need to set the content type of the manager as follows
manager.requestSerializer = [AFJSONRequestSerializer serializer];
try this
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
and in success block
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:manager.responseData options:kNilOptions error:nil];
self.clientToken = dic[#"customerID"];
NSLog(#"Client Token received.");
}
Here's my question:
NSDictionary *parameters = #{#"type": #"5", #"xq": #"a", #"apid": #"b", #"apsecret": #"c", #"astoken": #"d"};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer]; manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:[NSString stringWithFormat:#"text/plain; charset=UTF-8"] forHTTPHeaderField:#"Content-Type"];
if i use GET :
[manager GET:#"http://127.0.0.1/123.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"responseObject : %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error : %#", error);
}];
i can get $_GET['parameters'] value
but when i use POST :
[manager POST:#"http://127.0.0.1/123.php" parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"responseObject : %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"error : %#", error);
}];
i always get $_POST['parameters'] value is null.....
am i doing something wrong in the setting?
Change your 4th line of 1st code snippet to,
[manager.requestSerializer setValue:[AFJSONRequestSerializer serializer]];
sorry for all,
i found it's can work
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:#"http://127.0.0.1/123.php"]];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:#"123.php"
parameters:parameters
success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"responseObject : %#", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"error : %#", error);
}];
I'm trying to do a POST with action parameter called "#load".
To my webservice is a key need to show results: action:#load
How I can do this using AFNetworking framework? Here a sample of my wrong code:
First the constant declaration:
const NSString *BASE_URL = #"http://www.mywebservice.com/request.php";
Now the code:
-(void)requisitarEventos{
[smartEventos removeAllObjects];
NSString* url = [BASE_URL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[SVProgressHUD showWithStatus:#"Loading..." maskType:SVProgressHUDMaskTypeGradient];
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:#"#load",#"action", nil];
[manager POST:url parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
[self carregarEventos:responseObject];
[SVProgressHUD dismiss];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
[SVProgressHUD dismiss];
}];
}
I found the answer. The real problem of my code that's my Web Service doesn't give results of Content-Type in "application/json", but in "text/html".
I solve the problem using this code below:
NSMutableSet *contentTypes = [[NSMutableSet alloc] initWithSet:manager.responseSerializer.acceptableContentTypes];
[contentTypes addObject:#"text/html"];
manager.responseSerializer.acceptableContentTypes = contentTypes;
And the full code of my class:
-(void)callEvents{
[smartEvents removeAllObjects];
NSString* url = [NSString stringWithFormat:#"%#myService.php?action=load", BASE_URL];
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[SVProgressHUD showWithStatus:#"Loading..." maskType:SVProgressHUDMaskTypeGradient];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSMutableSet *contentTypes = [[NSMutableSet alloc] initWithSet:manager.responseSerializer.acceptableContentTypes];
[contentTypes addObject:#"text/html"];
manager.responseSerializer.acceptableContentTypes = contentTypes;
[manager GET:url parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
[self carregarEventos:responseObject];
[SVProgressHUD dismiss];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
[SVProgressHUD dismiss];
}];
}
please see this , I make a simple post method with callback ,
POST with URL parameters and JSON body in AFNetworking
this is always error with -1004 ( could not connect to server )
but the request in browser is working fine.
what's wrong with my code?
(url : "http://localhost:3000/v1/voice/version?appname=wevoice")
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:#"http://localhost:3000/v1/voice/version"
parameters:#{ #"appname": #"wevoice" }
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
You have to set the property baseURL on your request manager. Here is an example:
self.requestManager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:http://localhost:3000];
Later, in your concrete GET message to the manager, you'll only pass the relative URL path:
[self.requestManager GET:#"/v1/voice/version"
parameters:#{ #"appname": #"wevoice" }
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
And keep in mind, that, if you want to send your paramters as JSON, you'll need a request serializer:
self.requestManager.requestSerializer = [AFJSONRequestSerializer serializer];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setObject:#"wevoice" forKey:#"appname"];
[manager GET:#"http://localhost:3000/v1/voice/version"
parameters:dic
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
You can try this.May be the way you add Parameter is wrong.
Try this method. Hope it helps.
+ (void)getRequestWithURLStringWithSuccess:(void(^)(id object))successBlock andFail:(void(^)(NSString *errorMessage))failBlock {
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc]initWithBaseURL:[NSURL URLWithString:#"http://localhost:3000/v1/voice/version"]];
NSString *urlString = #"/version";
[manager GET:urlString parameters:#{ #"appname": #"wevoice" } success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}