How to pass dictionary in JSON , objective c - objective-c

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.

Related

AFNetwork Error:Error Domain=NSURLErrorDomain Code=-1012

I use the AFNetwork as below.
Firstly,I set the security policy as below:
-(AFSecurityPolicy*)customSecurityPolicy:(BOOL)isHTTPS
{
if (isHTTPS) {
NSString *cerPath = [[NSBundle mainBundle] pathForResource:#"ehub-mobile" ofType:#".cer"];
NSData *certData = [NSData dataWithContentsOfFile:cerPath];
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey];
[securityPolicy setPinnedCertificates:#[certData]];
[securityPolicy setValidatesDomainName:NO];
[securityPolicy setAllowInvalidCertificates:YES];
return securityPolicy;
}
else
{
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
return securityPolicy;
}
}
and the next is to set the manager:
-(void)UserLoginRequest:(NSString *)name Session:(NSString *)session
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.securityPolicy = [self customSecurityPolicy:YES];
NSString *uName = name;
NSString *uToken = session;
NSDictionary *parameters = #{#"username": uName,#"token":uToken};
ServerURLAddress *sua = [[ServerURLAddress alloc]init];
NSString *server = [NSString stringWithFormat:#"%#/session",
[sua serverURLAddress]];
server = [server stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[manager POST:server parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
[self DisableSingleTap];
NSString *lg_rep = operation.responseString;
[self SeizeTheLoginInfo:lg_rep];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#",error);
[self EnableSingleTap];
}];
}
But it just appears this error,and it occurred in the "failed" block where i use the NSLog function to print it:
Error Domain=NSURLErrorDomain Code=-1012 "(null)"
UserInfo={NSErrorFailingURLKey=https://xxx.xxx.com
I read a lot of article but i still couldn't find any solution.
Please give me some tips!
Try This,
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
[securityPolicy setValidatesDomainName:NO];
[securityPolicy setAllowInvalidCertificates:YES];
manager.securityPolicy = securityPolicy;

AFNetworking send array in JSON parameters of GET request

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);
}];

AFNetworking 2.5.4 sending file with PATCH request

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];
}

Opening of the second controller after a successful POST request

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

setDownloadProgressBlock in AFHTTPClient subclass

I created subclass of AFHTTPClient.
It works, but progress block return only final value (1.0). What should I change to get all the calculated values from setDownloadProgressBlock?
- (void)exploreVenuesCenter:(CLLocationCoordinate2D)coordinate inRadius:(int)radiusMeters success:(void (^)(NSArray *venues))success failure:(void (^)(NSError *error))failure progress:(void (^)(float progress))progress{
NSDictionary *parameters = #{#"limit": #"10",
#"client_id":kFoursquareClientID,
#"client_secret":kFoursquareClientSecret,
#"radius":#(radiusMeters).stringValue,
#"ll":[NSString stringWithFormat:#"%g,%g",coordinate.latitude, coordinate.longitude],
#"v":kFoursquareVersion};
NSMutableURLRequest *request = [self requestWithMethod:#"GET" path:#"venues/explore" parameters:parameters];
AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSArray *items = responseObject[#"response"][#"groups"][0][#"items"];
if (success)
{
success(items);
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) { if (failure) {
failure(error);
NSLog(error.localizedDescription);
} }];
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
//
float progressNo = ((float)totalBytesRead) / totalBytesExpectedToRead;
if (progress) {
progress(progressNo);
}
}];
[self enqueueHTTPRequestOperation:operation];
}