I am sending array as a parameter in AFNetworking GET Request.
My code is as follows:
- (void)getProductSearchResult:(NSString *)locale andSearchDict:(NSDictionary *)dictSearch{
NSString *strURL = [NSString stringWithFormat:#"%#/%#/search?%#",BASEURL,locale,APIFORMAT];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager GET:strURL parameters:dictSearch success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *jsonDict = (NSDictionary *)responseObject;
if ([jsonDict isKindOfClass:[NSDictionary class]] || [jsonDict isKindOfClass:[NSMutableDictionary class]]) {
if (self.delegate && [self.delegate respondsToSelector:#selector(API_ProductSearch_didSuccess:)]) {
[self.delegate API_ProductSearch_didSuccess:jsonDict];
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (self.delegate && [self.delegate respondsToSelector:#selector(api_ProductSearch_didFailWithError:)]) {
[self.delegate api_ProductSearch_didFailWithError:[NSError description]];
}
}];
}
The dictionary which I pass as parameter is as follows:
{
"brand_filter" = (
1
);
"category_filter" = (
438
);
"max_price" = "47.37188";
"min_price" = "1.95";
"price_currency" = USD;
"supplier_filter" = (
"Aakron Line"
);
}
URL which created is shown like
http://demo.aakronline.ca/app_dev.php/api/v1/en_us/search?_format=json&brand_filter[]=1&category_filter[]=438&max_price=48.04479&min_price=2.622917&price_currency=USD&supplier_filter[]=Aakron%20Line
The problem area in URL is array is not passed in proper format i.e.
brand_filter[]=1&category_filter[]=438 instead of brand_filter=[1]&category_filter=[438]
Can anyone tell me how to solve this mistake?
But I am not getting the successful response.
In afnetworking 3.0, instead of AFHTTPRequestOperationManager use AFHTTPSessionManager
NSString *strUrl = [NSString stringWithFormat:#"%#/%#/search?%#",BASEURL,locale,APIFORMAT];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:strUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"value: %#",responseObject);
//other code as it is
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"Error: %#",error);
}];
Related
I have to pass dictionary(hostListItemDict) to a server
BASE_URL : http:/123.com/PHP/
API_GET_FILE_NAME : server.php
Main File
-(void)toSendValuesToServer
{
[MiddlewareServerUtilityData SendDatasToServer:hostListItemDict ServerBaseUrl:BASE_URL andCompletion:^(NSError *error, id data) {
if (!error)
{
//NSLog(#"Data%#",data);
NSString *resourseType = [data objectForKey:#"success_msg"];
NSString *mess = [data objectForKey:#"msg"];
if ([resourseType.lowercaseString isEqualToString:#"success_msg"])
{
NSLog(#"Transaction uploaded successfully, with message %#",mess);
}
else
{
NSLog(#"###Error sending transaction,data = %#",data);
}
}
else
{
NSLog(#"#error uploading data %#",error.localizedDescription);
}
}];
}
Server.h File
typedef void (^GFWebServiceHandler)(NSError *error, id data);
#interface MiddlewareServerUtilityData : NSObject
+(void)SendDatasToServer:(NSDictionary *)hostListItemDict ServerBaseUrl:(NSString *)BaseUrl andCompletion:(GFWebServiceHandler)completion;
Server.m
#import "MiddlewareServerUtilityData.h"
#implementation MiddlewareServerUtilityData
+(void)SendDatasToServer:(NSDictionary *)hostListItemDict ServerBaseUrl:(NSString *)BaseUrl andCompletion:(GFWebServiceHandler)completion
{
NSString *strUrl = [NSString stringWithFormat:#"%#/%#",BaseUrl,API_GET_FILE_NAME];
[self createGETRequestWithParams:hostListItemDict urlString:strUrl andCompletion:completion];
}
+(AFHTTPRequestOperationManager *)createPOSTRequestWithParams:(NSDictionary *)hostListItemDict urlString:(NSString *)url_str andCompletion:(GFWebServiceHandler)completion
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializer];
responseSerializer.removesKeysWithNullValues = YES;
manager.responseSerializer = responseSerializer;
responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript", #"text/html", nil];
NSString *strEncodedUrl = [url_str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[manager POST:strEncodedUrl parameters:hostListItemDict success:^(AFHTTPRequestOperation *operation, id responseObject) {
completion(nil,responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
completion(error,nil);
}];
return manager;
}
+(AFHTTPRequestOperationManager *)createGETRequestWithParams:(NSDictionary *)hostListItemDict urlString:(NSString *)url_str andCompletion:(GFWebServiceHandler)completion
{
///strUrl = BASE_URL;
NSString *strUrlWithParams = [self stringByAppendingParams:hostListItemDict toUrlString:url_str];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializer];
responseSerializer.removesKeysWithNullValues = YES;
manager.responseSerializer = responseSerializer;
//manager.responseSerializer = [AFHTTPResponseSerializer serializer];
responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript", #"text/html", nil];
NSString *strEncodedUrl = [strUrlWithParams stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[manager GET:strEncodedUrl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
completion(nil,responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
completion(error,nil);
}];
return manager;
}
+(NSString *)stringByAppendingParams:(NSDictionary *)hostListItemDict toUrlString:(NSString *)url_str
{
if (url_str.length > 0) {
NSMutableString *strUrlWithParams = [NSMutableString stringWithString:url_str];
if (hostListItemDict .count > 0) {
///Append ? for first param
[strUrlWithParams appendString:#"?"];
for (id paramName in [hostListItemDict allKeys]) {
///Get value associated to param name
id paramVal = [hostListItemDict objectForKey:paramName];
///Append Param
[strUrlWithParams appendFormat:#"%#=%#&",paramName,paramVal];
}
///Remove & from last
NSRange lastCharRange = NSMakeRange(strUrlWithParams.length - 1, 1);
[strUrlWithParams deleteCharactersInRange:lastCharRange];
}
return strUrlWithParams;
}
return nil;
}
error uploading data The data couldn’t be read because it isn’t in the correct format.
Here's my code
AFHTTPSessionManager *manger = [[AFHTTPSessionManager alloc] init];
[manger GET:requestUrl parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
I got two error from Xcode.
Unknown type name 'id'
Incompatible block pointer types sending 'void (^)(NSURLSessionDataTask * _Nonnull __strong, int)' to parameter of type 'void (^ _Nullable)(NSURLSessionDataTask * _Nonnull __strong, id _Nullable __strong)'.
Why is this happen?I had imported AFNetworking file in my header file.My Xcode version is 8.2,and AFNetworking version is 3.1.When I put this code snippet in my other project,there was no error.That was really confused me.Anyone can help?
I used Carthage to import AFNetwoking,still the same error.:(
Final solution:I recreate the project.And migrate the old code to new project.It works.But still know the reason why the old version code not work.
your method should like this
-(void)callWebserviceWithParams:(NSMutableDictionary *)_params
action:(NSString *)_action
success:(void (^)(id))_success
failure:(void (^)(NSError *))_failure
{
if ([[AFNetworkReachabilityManager sharedManager] isReachable]) {
//AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSString *url = [BASE_URL stringByAppendingString:_action];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:url]];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript",#"text/html", nil];
[manager POST:url parameters:_params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"response = %#", responseObject);
if( _success )
{
_success( responseObject ) ;
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"error = %#", error);
if( _failure )
{
_failure( error) ;
}
}];
}
}
Using AFNetworking for communication between REST API and my application I ran into a strange behaviour wenn trying to upload an image with PATCH request.
I use following code:
- (void) uploadImage: (UIImage *)image {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{};
AFHTTPRequestSerializer *requestSerializer = [manager requestSerializer];
NSError *e = nil;
NSMutableURLRequest *request = [requestSerializer multipartFormRequestWithMethod:#"PATCH"
URLString:requestString
parameters:parameters
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:UIImagePNGRepresentation(image)
name:#"image"
fileName:#"image.png"
mimeType:#"image/png"];
} error:&e];
[manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog("OK");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog("FAILED");
}];
}
Neither success not failed block of operation will be reached.
Wenn I change the request method to POST everything works fine, but the Server accepts only PATCH method for this case.
Am I doing something wrong?
I finally found a solution for my question:
- (void)uploadImage:(UIImage *)image
withSuccess:(SomeSuccessBlock)success
failure:(SomeFailureBlock)failure {
NSString *requestString = "Some url";
NSError *e = nil;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFHTTPRequestSerializer *requestSerializer = [manager requestSerializer];
NSMutableURLRequest *request = [requestSerializer multipartFormRequestWithMethod:#"POST" URLString:requestString parameters:#{}
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:UIImagePNGRepresentation(image)
name:#"user[avatar]"
fileName:#"avatar.png"
mimeType:#"image/png"];
} error:&e];
if (e && failure) {
failure(e);
return;
}
[request setHTTPMethod:#"PATCH"];
[request setValue:#"PATCH" forHTTPHeaderField:#"X-HTTP-Method-Override"];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success) {
success();
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (failure) {
failure(error);
}
}];
[operation start];
}
I only learn Obj-c. I'm sending a login and password, get back to html page, how do I open the page after the request and closed loginWindowController? is the request itself :
NSString *myLogin = usernameTextField.stringValue;
NSString *myPassword = passwordTextField.stringValue;
NSString *myFlash = flashpasswordTextField.stringValue;
NSString *myNid = #"123456";
NSString *urlString = #"http://neverlands.ru/game.php";
NSString *ua = #"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36";
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
AFHTTPRequestSerializer * requestSerializer = [AFHTTPRequestSerializer serializer];
[requestSerializer setValue:ua forHTTPHeaderField:#"User-Agent"];
manager.requestSerializer = requestSerializer;
AFHTTPResponseSerializer * responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer = responseSerializer;
NSDictionary *parameters = #{#"player_nick": myLogin, #"player_password": myPassword};
[manager POST:urlString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
//Условия после запроса 1
if ([operation.responseString rangeOfString:#"NeverLands: Земли, которых нет... - Второй пароль"].location == NSNotFound) {
NSLog(#"Неверный логин или пароль");
} else {
NSDictionary *parameters = #{#"flcheck": myFlash, #"nid": myNid};
[manager POST:urlString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
//Условия после запроса 2
if ([operation.responseString rangeOfString:#"NeverLands: Земли, которых нет... - бесплатная браузерная онлайн игра в стиле фэнтези"].location == NSNotFound) {
NSLog(#"Неверный флеш пароль");
} else {
mainWindowController = [[MainWindowController alloc] initWithWindowNibName:#"MainWindow"];
[mainWindowController showWindow:self];
[mainWindowController addWebView:[NSURL URLWithString:urlString]];
NSLog(#"Авторизация произведена");
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
what to write here that would have opened the current session?
mainWindowController = [[MainWindowController alloc] initWithWindowNibName:#"MainWindow"];
[mainWindowController showWindow:self];
[mainWindowController addWebView:[NSURL URLWithString:HERE]];
I tried [mainWindowController addWebView:[NSURL URLWithString:urlString]]; But open page with a new session and writes that the username and password is not entered.
It looks like you are making the same post request, with the same body, but looking for 2 different contents in the response?
You should just make 2 checks to the body of the response
NSString *importantStuff1 = #"NeverLands: Земли, которых нет... - Второй пароль";
NSString *importantStuff2 = #"NeverLands: Земли, которых нет... - бесплатная браузерная онлайн игра в стиле фэнтези";
if (([operation.responseString rangeOfString:importantStuff1].location == NSNotFound) &&
([operation.responseString rangeOfString:importantStuff2].location == NSNotFound))
{
NSLog(#"Couldn't find the important stuff needed");
}
else
{
mainWindowController = [[MainWindowController alloc] initWithWindowNibName:#"MainWindow"];
[mainWindowController showWindow:self];
[mainWindowController addWebView:[NSURL URLWithString:urlString]];
NSLog(#"Авторизация произведена");
}
pardon the variable names I have no idea what those words are haha
I tried to make GET HTTP response. I need to get the html code for the subsequent parsing, but responseObject is nil.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager GET:#"http://www.example.com/" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError *error;
HTMLParser *parser = [[HTMLParser alloc] initWithString:responseObject error:&error];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
For get html code we will need to build a custom response serializer to decode the NSData response from the web server into a NSString. We will need to subclass AFHTTPResponseSerializer and implement the following method:
- (id)responseObjectForResponse:(NSURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)error
{
return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
}
Why for example you have not use this solution below instead of subcalssing. It does the same thing, but you don't need to create additional files, just for overload one method.
So you can just add encoding your responseObjet in the block for example, and it will work as well. I am using POST in my example but it should work with GET in the same way but without parameters, but idea of the just conversation.
+ (void)makeRequestWithParams:(NSDictionary *)params
success:(OperationCompletionBlock)success
failure:(OperationCompletionBlock)failure
{
NSString *path = #"http://www.example.com/";
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFCompoundResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager POST:path parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString* encodedString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"%#", encodedString);
success(nil);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
failure(nil);
}];
}