AFNetwork Error:Error Domain=NSURLErrorDomain Code=-1012 - objective-c

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;

Related

How to pass dictionary in JSON , 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.

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

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

how to change my synchronous to asynchronous call in Objective-C?

hi friend i am beginner for objective-c.i have slow response from server side due to synchronous call. i analysed in google the call may be asynchronous means the response speed will be high, but i don't know much about NSURLConnection and GCD. so please help me how to change my call asynchronous . see my code below`
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString* oldToken = [self deviceToken];
NSString *newToken = [[[[deviceToken description]stringByReplacingOccurrencesOfString:#"<"withString:#""]
stringByReplacingOccurrencesOfString:#">" withString:#""]
stringByReplacingOccurrencesOfString: #" " withString: #""];
NSLog(#"My token is: %#", newToken);
[self setDeviceToken:newToken];
if (![newToken isEqualToString:oldToken])
{
[self calur:newToken];
}
}
- (NSString*)deviceToken{
return [[NSUserDefaults standardUserDefaults] stringForKey:#"deviceid"];
}
- (void)setDeviceToken:(NSString*)token{
[[NSUserDefaults standardUserDefaults] setObject:token forKey:#"deviceid"];
}
//This function used to store a notification device id to our notification databae
-(void)calur:(NSString *)device
{
NSString *post =[NSString stringWithFormat:#"deviceId=%#",device];
NSString *hostStr = #"https://myserver.com/Ver_2_0/notification/check.php?";
NSError *error = nil;
NSString *nocon=[NSString stringWithContentsOfURL:[NSURL URLWithString:hostStr]encoding:NSUTF8StringEncoding error:&error];
if (nocon == nil)
{
NSLog(#"NO Connection");
}
else
{
hostStr = [hostStr stringByAppendingString:post];
NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
NSLog(#"hostStr=%#",hostStr);
NSLog(#"serverOutput = %#",serverOutput);
NSLog(#"dataURL=%#",dataURL);
// NSData *dataurl=dataURL;
if([serverOutput isEqualToString:#"Token Updated Successfully"])
{
NSLog(#"badge updated");
}
else
{
NSLog(#"serverOutput = %#",serverOutput);
NSLog(#"not registered");
}
[serverOutput release];
}
}`
if (nocon == nil)
{
NSLog(#"NO Connection");
}
else
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
hostStr = [hostStr stringByAppendingString:post];
NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
NSLog(#"hostStr=%#",hostStr);
NSLog(#"serverOutput = %#",serverOutput);
NSLog(#"dataURL=%#",dataURL);
// NSData *dataurl=dataURL;
if([serverOutput isEqualToString:#"Token Updated Successfully"])
{
NSLog(#"badge updated");
}
else
{
NSLog(#"serverOutput = %#",serverOutput);
NSLog(#"not registered");
}
[serverOutput release];
});
}
a little snippet:
#import "AFNetworking.h"
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:self.value, #"POSTvar", nil];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL: [NSURL URLWithString:#"http://your.address"]];
NSURLRequest *request = [client requestWithMethod:#"POST" path:nil parameters:params];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
// do some with JSON
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
}];
[operation start];
});
AFNetworking github

Facebook in iOS6.0 use SLRequest to upload a photo failed anyway

Here Comes my Objc code:
ACAccountStore *facebookaccount = [[ACAccountStore alloc] init];
ACAccountType *facebookaccountType = [facebookaccount accountTypeWithAccountTypeIdentifier: ACAccountTypeIdentifierFacebook];
// Specify App ID and permissions
NSDictionary *options = #{ ACFacebookAppIdKey: #"1234567899876543", ACFacebookPermissionsKey: #[#"publish_stream"], ACFacebookAudienceKey: ACFacebookAudienceFriends };
[facebookaccount requestAccessToAccountsWithType:facebookaccountType options:options completion:^(BOOL granted, NSError *error) {
if(granted) {
NSArray *accountsArray = [facebookaccount accountsWithAccountType:facebookaccountType];
if ([accountsArray count] > 0) {
ACAccount *facebookAccount = [accountsArray objectAtIndex:0];
NSString *sendmessage = #"Face";
NSData *myImageData = UIImagePNGRepresentation(imageSource);
SLRequest *facebookRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook requestMethod:SLRequestMethodPOST URL:[NSURL URLWithString:#"https://graph.facebook.com/me/photos"] parameters:nil];
[facebookRequest addMultipartData:myImageData withName:#"source" type:#"multipart/form-data" filename:nil];
[facebookRequest addMultipartData:[sendmessage dataUsingEncoding:NSUTF8StringEncoding] withName:#"message" type:#"multipart/form-data" filename:nil];
[facebookRequest setAccount:facebookAccount];
[facebookRequest performRequestWithHandler:^(NSData* responseData, NSHTTPURLResponse* urlResponse, NSError* error) {
if (error == nil) {
NSLog(#"responedata:%#", [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]);
}else{
NSLog(#"%#",error.description);
}
}
}
else
{
NSLog(#"error description : %#",[NSString stringWithFormat:#"%#", error.localizedDescription]);
}
}];
Finally I get these respone data:
responedata:{"error":{"message":"(#324) Requires upload file","type":"OAuthException","code":324}}
Help me please!!!
I can successfully upload a photo by including a file name in addMultipartData and by passing the message as part of the SLRequest options.
code:
NSDictionary *parameters = #{#"message": sendmessage};
SLRequest *facebookRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodPOST
URL:[NSURL URLWithString:#"https://graph.facebook.com/me/photos"]
parameters:parameters];
[facebookRequest addMultipartData: myImageData
withName:#"source"
type:#"multipart/form-data"
filename:#"TestImage"];
facebookRequest.account = facebookAccount;
[facebookRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
// Log the result
}];