AFNetworking 3.0 iOS 9.3.5 reject some SSL - ios

This happened only in iOS 9.3.5 (not sure about other 9 or below), not occur in iOS 10.x.
When I use AFNetworking to connect to an API URL, it just run into failure callback with error like below:
LOG: Error Domain=NSURLErrorDomain Code=-1004 "Could not connect to
the server." UserInfo={NSErrorFailingURLStringKey=APIURL,
_kCFStreamErrorCodeKey=-2200, NSErrorFailingURLKey=APIURL, NSLocalizedDescription=Could not connect to the server.,
_kCFStreamErrorDomainKey=4, NSUnderlyingError=0x16146990 {Error Domain=kCFErrorDomainCFNetwork Code=-1004 "(null)"
UserInfo={_kCFStreamErrorDomainKey=4, NSErrorPeerAddressKey={length =
16, capacity = 16, bytes = 0x100201bb253ce7160000000000000000},
_kCFStreamErrorCodeKey=-2200}}}
When I paste the API to safari browser (same device), it ask me to trust a certificate or something like that, so I'm afraid there's something wrong in the configuration in the app.
My call for URL:
self.sessionManager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseUrl sessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
self.sessionManager.securityPolicy.allowInvalidCertificates = YES;
self.sessionManager.securityPolicy.validatesDomainName = NO;
self.sessionManager.requestSerializer.timeoutInterval = timeout;
self.sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
// Call API:
[self.sessionManager POST:path parameters:dictParams progress:nil success:^(NSURLSessionTask *task, id responseObject) {
// success block
} failure:^(NSURLSessionTask *task, NSError *error) {
// failure block
}
I've even set NSAllowsArbitraryLoads=true in App Transport Security Settings inside info.plist.
How to fix this? I found this question have the similar error, but I'm not so sure. I don't have access to the API host and in ios 10.x it works just fine. When using postman it works too.

Related

NSURLSession Not Reaching Server

I've created an iPhone app for my Arduino, and basically, the Arduino can communicate over the local network using very basic commands provided by a 3rd party REST API. I've successfully been able to use the API via my computer's web browser, but when trying to send a request to it via an iPhone app, it doesn't seem to want to work. Also keep in mind, I can get the API to respond properly via Safari on my iPhone. The only response I'm getting (inside the console) is:
{ URL: http://192.168.0.216/mode/7/0 } { status code: 200, headers {
Connection = close;
"Content-Type" = "application/json";
} } : <7b226d65 73736167 65223a20 2250696e 20443722 6964223a 20223030 38222c20 226e616d 65223a20 226d6967 6874795f 63617422 2c202263 6f6e6e65 63746564 223a2074 7275657d 0d0a>
The API is indeed supposed to return JSON data, but the response on the web browser actually affects my Arduino's LED.
Code for Turning the LED on
NSURL *modeSet = [NSURL URLWithString:[NSString stringWithFormat:#"http://192.168.0.216/digital/%d/1", _pin]];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:modeSet
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
NSLog([NSString stringWithFormat:#"%# : %#", response, data]);
}] resume];
EDIT: I decided to print out the 'Error' variable to see if it was holding anything back from me, and I found this:
Error Domain=NSURLErrorDomain Code=-1001 "The operation couldn’t be completed.
(NSURLErrorDomain error -1001.)" UserInfo=0x17807b840 {NSErrorFailingURLStringKey=http://192.168.0.216/mode/7/o,
NSUnderlyingError=0x178449450 "The operation couldn’t be completed.
(kCFErrorDomainCFNetwork error -1001.)", NSErrorFailingURLKey=http://192.168.0.216/mode/7/o}
Pre-iOS 9 Answer
Answering my own question so if anyone finds this by Google sometime, they won't have to ask.
All I did was formatted my string correctly with NSUTF8Encoding like so:
NSString *modeSetString = [[NSString stringWithFormat:#"http://192.168.0.216/mode/%d/o", _pin] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *modeSet = [NSURL URLWithString:modeSetString];
iOS 9 Update
stringByReplacingPercentEscapesUsingEncoding: is now deprecated and stringByRemovingPercentEncoding should be used instead like so:
NSString *modeSetString = [[NSString stringWithFormat:#"http://192.168.0.216/mode/%d/o", _pin] stringByRemovingPercentEncoding];
NSURL *modeSet = [NSURL URLWithString:modeSetString];

iOS: Encountered an error kCFURLErrorUserCancelledAuthentication -1012?

In iOS application is required to sign a certificate request, which had previously been obtained. When I try to run a query catch this error:
kCFURLErrorUserCancelledAuthentication -1012.
The documentation says:
kCFURLErrorUserCancelledAuthentication The connection failed because
the user cancelled required authentication.
Implemented as follows:
- (void)startConnection {
NSString *serverURL = #"host.ru/method";
MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:serverURL customHeaderFields:nil];
MKNetworkOperation *op = [engine operationWithPath:nil params:nil httpMethod:#"GET" ssl:YES];
NSString *thePath = [[NSBundle mainBundle] pathForResource:#"client" ofType:#"p12"];
[op setShouldContinueWithInvalidCertificate:YES];
op.clientCertificate = thePath;
op.clientCertificatePassword = #"1234qwerty";
[op addCompletionHandler:^(MKNetworkOperation *operation) {
NSLog(#"[operation responseData]-->>%#", [operation responseString]);
}errorHandler:^(MKNetworkOperation *errorOp, NSError* err) {
NSLog(#"MKNetwork request error : %#", [err localizedDescription]);
}];
[engine enqueueOperation:op];
}
What am I doing wrong?
P.S.
Certificate, which try to sign the request has been received in advance. It tested separately in the browser, it's okay.
An application for android to the same server requests are normally the same scheme.
This can happen when your connection sends a request for an authentication challenge.
A possible cause is that the site's certificate is invalid/untrusted and you have opted not to accept invalid certificates.

Code=-1005 "The network connection was lost

am my app made and doing POST request using the AFHTTPRequestOperationManager.
I have 4 urls which all works fine with the server, they are pretty much the same format, same usage, etc. So I coded them the same as well.In actually fact I only have an if statement to determine which url I shall use for the same method I made, so every time I request any of the urls with POST I use the same one.
For 3 of them they just work perfectly, but the 4th one, no matter how I use it, it always gets me
"Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."
I tested with this url on my server, it works fine. There's nothing wrong with the server, but AFNetworking just won't send this request out. If its a true DC then my other URLs are still working fine?
I run this app on IOS8 beta2, I don't know if the beta is causing the issue? (Which I doubt)
pls help ...
Sample code
#define SERVER_URL #"http://54.187.63.214/"
#define SERVER_LIKE_URL #"candidate_likeJob/"
#define SERVER_DISLIKE_URL #"candidate_dislikeJob/"
- (void) likeOrSkipJob:(BOOL)isLike{
UserSetting *setting = [UserSetting getSetting];
UFCompany *matchedCompany = [matchedCompanies lastObject];
UFJob *matchJob = [matchedCompany.jobs firstObject];
NSLog(#"like job : %#", matchJob.position);
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] init];
NSString *likeURL = [NSString stringWithFormat:#"%#%#",SERVER_URL,isLike? SERVER_LIKE_URL: SERVER_DISLIKE_URL];
NSDictionary *params = [[NSDictionary alloc] initWithObjectsAndKeys: setting.ufind_id, #"candidate_id", matchJob.job_id, #"job_id", nil];
NSLog(#"Request URL: %# with params %#", likeURL, params);
[manager POST:likeURL parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *response) {
NSString *status = [response objectForKey:#"status"];
//if server tell status ok
if ([status isEqualToString:#"ok"]) {
NSLog(#"%# job success", isLike? #"Like":#"Dislike");
//update the work if like succeed
[matchedCompanies removeLastObject];
[self updateMatchScreen];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"like request failed %#", error);
}];
}
The SERVER_LIKE_URL is generating the -1005 "connection lost", but SERVER_DISLIKE_URL always work.
Reset content and setting of your iOS simulator, Recompile and run the app on iOS Simulator
Restarting the simulator and Clear & Build, fixed the issue for me.
Try to make Your requests synchronously (one after one)
I was having the same error message using Xcode 6.2 and running a map app (I could not load the map), resetting the simulator etc did not solve the problem, however I turned off the anti virus and web threat detector and the map loaded immediately with no error message. I then turned the anti virus and web threat detector back on and the app worked OK on the simulator and loaded the map, the error message still came up though but after 2 error messages the map loaded so it seems that the antivirus and web threat detector were treating the simulator internet connection request as a threat.

kCFErrorDomainCFNetwork error -1005 AFNetworking

I have a singleton class:
+(id)sharedClient
{
static HackerNewsClient *__instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSURL *url = [NSURL URLWithString:#"http://node-hnapi.herokuapp.com"];
__instance = [[HackerNewsClient alloc] initWithBaseURL:url];
});
return __instance;
}
And in a controller I am calling this like so:
[[HackerNewsClient sharedClient]GET:#"/news"
parameters:nil
success:^(NSURLSessionDataTask *task, id responseObject) {
NSArray *posts = [self parseEpisodeJSONData:responseObject];
completion(posts);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"ERROR: %#", error);
}];
The url this creates is http://node-hnapi.herokuapp.com/news which is a valid and working url. But the error message returned is
2014-07-08 08:51:15.942 hn[27435:1627947] ERROR: Error Domain=NSURLErrorDomain Code=-1005 "The operation couldn’t be completed. (NSURLErrorDomain error -1005.)" UserInfo=0x10ba2bf70 {NSErrorFailingURLStringKey=http://node-hnapi.herokuapp.com/news, NSErrorFailingURLKey=http://node-hnapi.herokuapp.com/news, _kCFStreamErrorDomainKey=1, _kCFStreamErrorCodeKey=57, NSUnderlyingError=0x10ba22ff0 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1005.)"}
I can't work out what would be causing this issue. Thanks
this error always appeared when the connection fails ..
if your connection work fine just try to restart the iPhone simulator spicily with iPhone 6 simulator ...!
check link : NSURLConnection GET request returns -1005, "the network connection was lost"
Look in the CFNetworkErrors header files for CFNetwork Framework.
In Xcode navigate to
ProjectName > Frameworks > CFNetwork.framework > Headers > CFNetworkErrors.h

AFNetworking request with Basic Auth works at first but fails after a few minutes

I have an app with data fed from an AFNetworking request with basic auth. I have a refresh button to perform the same function used to initially feed the data. This all works, but after a couple minutes it doesn't.
My code:
- (void) refreshData
{
// Show loading
NSLog(#"Refreshing...");
[LoadingView initInView:self.view];
// Get session data for auth key
SessionHelper *session = [SessionHelper sharedInstance];
// Setup request
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager setRequestSerializer:[AFHTTPRequestSerializer serializer]];
[manager.requestSerializer clearAuthorizationHeader];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:session.authKey password:#""];
NSString *url = #"https://myurl.com/getdata";
[manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.data = [[NSMutableArray alloc] init];
[self.data addObjectsFromArray:responseObject];
[self.tableView reloadData];
[LoadingView remove];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [error description]);
[operation cancel];
}];
}
Works repeatedly fine at first, but after a few minutes it hangs with the loading screen (from LoadingView) and the error:
Error: Error Domain=NSURLErrorDomain Code=-1012 "The operation
couldn’t be completed. (NSURLErrorDomain error -1012.)"
UserInfo=0x8a5ed20 {NSErrorFailingURLKey=https://myurl.com/getdata,
NSErrorFailingURLStringKey=https://myurl.com/getdata}
I thought maybe I needed to do clearAuthorizationHeader or something, but no go. Any ideas? Thanks!
Update: Logging operation.response.statusCode in the error message
gives me 0.
Update 2: Using AFNetworkActivityLogger gives me this after it starts failing:
2014-02-26 13:23:02.206 MyApp iPad[4087:60b]
GET 'https://myurl.com/getdata' 2014-02-26 13:23:02.646 MyApp
iPad[4087:60b] [Error] GET '(null)' (0) [0.4332 s]: Error
Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be
completed. (NSURLErrorDomain error -1012.)" UserInfo=0x17d9a990
{NSErrorFailingURLKey=https://myurl.com/getdata,
NSErrorFailingURLStringKey=https://myurl.com/getdata} 2014-02-26
13:23:02.648 MyApp iPad[4087:60b] Error: Error Domain=NSURLErrorDomain
Code=-1012 "The operation couldn’t be completed. (NSURLErrorDomain
error -1012.)" UserInfo=0x17d9a990
{NSErrorFailingURLKey=https://myurl.com/getdata,
NSErrorFailingURLStringKey=https://myurl.com/getdata}, Status Code: 0
Seems the URL is being sent as (null)...
Turns out, even though the GoDaddy certificate I'm using looks to be valid and supported by iOS 7 according to http://support.apple.com/kb/HT5012, adding this bit solves the problem. Seems to kind of defeat the purpose, but it works. I won't accept this answer yet in case someone can give some insight / something more helpful.
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
securityPolicy.allowInvalidCertificates = YES;
manager.securityPolicy = securityPolicy;

Resources