NSURLErrorDomain Code=-1012 The operation couldn’t be completed - ios

I am getting the following error when running my code from the xcode.
Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be completed. (NSURLErrorDomain error -1012.)" UserInfo=0x17166b740
{NSErrorFailingURLStringKey=https://..../move/resource/v1/user/me/activity/summary?start_date=2015-01-21&end_date=2015-01-14&detail=true,
NSUnderlyingError=0x17405b630 "The operation couldn’t be completed.
(kCFErrorDomainCFNetwork error -1012.)",
NSErrorFailingURLKey=https://..../move/resource/v1/user/me/activity/summary?start_date=2015-01-21&end_date=2015-01-14&detail=true}
Here is my Code
NSString *urlSummaryString = [[NSString stringWithFormat: #"%#summary?start_date=%#&end_date=%#&detail=true", kMisfitCloudEndpoint, strStartDate,strEndDate] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
__block NSMutableDictionary *responseDict = [NSMutableDictionary dictionary];
__block NSError *error = nil;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlSummaryString] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0];
[request setValue:#"access_token" forHTTPHeaderField:self.misfitAccessToken];
[request setHTTPMethod:#"GET"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if(connectionError){
// Handle the connection error
return ;
}}];
Can any one help me what is wrong here. Is it something related to SSL Certificate on the server and is related to the security. When I use CocoaRestClient to make my request it works perfectly.
Can some body explain me in detail what cause this problem or if any body can have the solution for this. I have to use [NSURLConnection sendAsynchronousRequest] method. I am using Xcode 6.1 and ios 8.1.2

In my case i am making a very silly mistake.
[request setValue:self.misfitAccessToken forHTTPHeaderField:#"access_token" ];
This solved my problem

This is kCFURLErrorUserCancelledAuthentication error,
-10xx errors are of the CFNetworkErrors enum.
Name of this constant is pretty selfexplanatory. Server cancelled authentication for some reason

Related

Getting Frequent Time out

I am Getting Frequent Timeout errors (not always but some times)although the timeout is set 500 .Chekd the same on postman too Two things one in postman the connection is always keep alive and second one is "The request timed out" coming randomly not always .BUt it just happen as soon as screen opened as i have called the webservice in ViewDidload so it has to at-least wait a bit .before throwing the error
what might be the possible cause for this
Below is my implementation for request
+(void)placeRequest:(NSString *)action parametersString:(NSString*)postDataStr withHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))ourBlock {
NSString *urlString = [NSString stringWithFormat:#"%#%#", IOS_BASE_URL, action];
NSURL *url = [NSURL URLWithString:urlString];
NSDictionary *headers = #{ #"content-type": #"application/x-www-form-urlencoded",#"Connection":#"keep-alive", #"cache-control": #"no-cache"};
NSString *parmetersToPost=[NSString stringWithFormat:#"%#%#",postDataStr,[AppDelegate UserWebCommeParmeters] ];
NSMutableData *postData = [[NSMutableData alloc] initWithData:[parmetersToPost dataUsingEncoding:NSUTF8StringEncoding]];
NSString *logString=[NSString stringWithFormat:#"Here the Url is : \n\n\n\n %# \n\n\n\n\nAction Used is :========> %# \n\n\n\n\n and the Parmeter posted are :=============> %#",IOS_BASE_URL,action,parmetersToPost];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:500.0];
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:postData];
NSLog(#"All header Sent are %#", request.allHTTPHeaderFields);
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:ourBlock] resume];
}
Calling this method as below in viewdidload
[HttpRequest placeRequest:#"check_value" parametersString:postData withHandler:^(NSData *receivedData, NSURLResponse *response, NSError *err){
}];
Error Domain=NSURLErrorDomain Code=-1001 "The request timed out."
UserInfo={NSErrorFailingURLStringKey=http://cms.xa.com/apps/xa/ax/myFuntion,
_kCFStreamErrorCodeKey=-2102, NSErrorFailingURLKey=http://cms.xa.com/apps/xa/ax/myFuntion,
NSLocalizedDescription=The request timed out.,
_kCFStreamErrorDomainKey=4, NSUnderlyingError=0x16587760 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)"
UserInfo={_kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102}}}

Passing JSON as parameter in URL objective-c

I have following web service url:
NSString *url = #"https://api.parse.com/1/classes/Cinema?keys=name,rows,column&where={\"location\":{\"__type\":\"Pointer\",\"className\":\"Location\",\"objectId\":\"gSEpGR28iT\"}}";
here parameter for where is itself in JSON format
Problem is when i consume this web service using following code it gives error:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
request.HTTPMethod = #"GET";
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:PARSE_APPLICATION_ID_VALUE forHTTPHeaderField:PARSE_APPLICATION_ID_KEY];
[request addValue:PARSE_REST_ID_VALUE forHTTPHeaderField:PARSE_REST_ID_KEY];
[NSURLConnection sendAsynchronousRequest:command.request
queue:self.operationQueue
completionHandler:^(NSURLResponse *response,
NSData *data,
NSError *error)
{
...
}]
Error: Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL"
UserInfo={NSUnderlyingError=0x7c989590 {Error
Domain=kCFErrorDomainCFNetwork Code=-1002 "unsupported URL"
UserInfo={NSLocalizedDescription=unsupported URL}},
NSLocalizedDescription=unsupported URL}
If i use same web service without where parameter i.e. only https://api.parse.com/1/classes/Cinema?keys=name,rows,column code works fine. I don't know why a parameter in json format is causing problem. Any help would be highly appreciated. Thanks.

When I query the google datastore my response is 'not found'

When I query the google datastore (after authenticating from iOS) - the response from my NSURLConnection is 'Not Found'. I am expecting to see something like 'missing parameters from post', or like on this site, where it says '503 service unavailable' or something like that.
https://developers.google.com/apis-explorer/#s/datastore/v1beta2/datastore.datasets.runQuery
The code is
NSString *url = #"https://www.googleapis.com/datastore/v1beta2/datasets/MYDATASETID/runQuery?key=MY_API_KEY";
NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
NSString *stringData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"response is %#", stringData);
}];
Where MYDATASETID is my actual project name. And I am getting these instructions for this url from the site:
https://developers.google.com/datastore/docs/apis/v1beta2/datasets/runQuery
thanks
The answer for me to get a response was to set 'POST' as the HTTP Method, for example:
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:fullUrl]];
[req setHTTPMethod:#"POST"];
[req setHTTPBody:[someData dataUsingEncoding:NSUTF8StringEncoding]];
Note though that this does not fully solve my challenge because although I get a response, the response from my variable stringData is
Login Required
And the error in NSError *connectionError is
Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be completed. (NSURLErrorDomain error -1012.)" UserInfo=0x8e20690 {NSErrorFailingURLKey=https://www.googleapis.com/datastore/v1beta2/datasets/MY_APP_ID/runQuery?key=MY_APPS_API_KEY, NSErrorFailingURLStringKey=https://www.googleapis.com/datastore/v1beta2/datasets/MY_APP_ID/runQuery?key=MY_APPS_API_KEY, NSUnderlyingError=0x8d6f120 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1012.)"}

get method in ios json parsing issue

I just want to hit URL :
http://kiascenehai.pk/rest_api/todayEvents/api-key/Of7NU7Jimh665D5G5VwO2eKO69sWv9lf/format/json
and parameter is city_id.i.e: /city_id/1 but; compiler creates Error
Domain=NSURLErrorDomain Code=-1002
"unsupported URL"
or
error 300;
so what shall be best way to pass arguments in a method in objective c???it also causes Error Domain=kCFErrorDomainCFNetwork Code=303 "The operation couldn’t be completed.
(kCFErrorDomainCFNetwork error 303
It will be pleasure for me if any one can reply me fast as possible.
Unable to reproduce issue you have mentioned, Probably the issue 'll be not because of the URL or parameters you used.
This is one of the best way to handle GET web service call and parsing data from the response, here i implemented the web call with your URL and params,
// Server data fetch
- (void)getDataForCityId:(NSInteger)cityId
{
NSMutableString *urlString = [#"http://kiascenehai.pk/rest_api/todayEvents/api-key/Of7NU7Jimh665D5G5VwO2eKO69sWv9lf/format/json/city_id/" mutableCopy];
[urlString appendFormat:#"%d", cityId];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0];
[request setHTTPMethod:#"GET"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if (data)
{
id jsonObj = [self parseJSON:data];
}
}];
}
// Method parses the JSON Data Received
- (id)parseJSON:(NSData *)data
{
id jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
return jsonData;
}
The jsonObj parsed form the response is as

IOS - Same ASIHTTPRequest code doesn't work only one method

In my project I make the other functions work with this code. But for this method I cannot make it work. I did copy-paste all this code for different methods(changing URL ,Result). The parameters of this methods are only int and string.
I always correct the wcf method from SOAP UI and .NET project.It works correct.
I only cannot make this code work for this method.
The [request responseString] returns a patient's information. Please help me. Thank you.
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:HASTAARAIP]];
NSData *myPostData = [[NSString stringWithFormat:#"{\"kat\":0,\"oda\":0,\"hastaAdi\":\"KAI\",\"protokolNo\":0,\"yatanAyaktan\":1}"] dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData *myMutablePostData = [[NSMutableData alloc]initWithData:myPostData];
[request setPostBody:myMutablePostData];
[request setRequestMethod:#"GET"];
[request addRequestHeader:#"Content-Type" value:#"application/json"];
[request setDelegate:self];
[request startSynchronous];
Here is some things that can make you understand.
With this code the [request responseString] and [request responseStatusMessage] is null. But if I remove the line where the addRequestHeader, it says for responseStatusMessage HTML/1.1HTTP/1.1 404 Not Found 404. I didn't understand why it gives this 404 error. This request type works for the other methods.
The ıp is like http://.../rest/<methodname>
Added log for a part of responsestring`:
The server encountered an error processing the request. The exception
message is 'The incoming message has an unexpected message format
'Raw'. The expected message formats for the operation are 'Xml';
'Json'. This can be because a WebContentTypeMapper has not been
configured on the binding. See the documentation of
WebContentTypeMapper for more details.'. See server logs for more
details. The exception stack trace is:
Updated:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:HASTAARAIP]];
[request setPostValue:#"0" forKey:#"kat"];
[request setPostValue:#"0" forKey:#"oda"];
[request setPostValue:#"KAI" forKey:#"hastaAdi"];
[request setPostValue:#"0" forKey:#"protokolNo"];
[request setPostValue:#"1" forKey:#"yatanAyaktan"];
[request startSynchronous];
But for responseString the logs:
The server encountered an error processing the request. The exception message is 'The incoming message has an unexpected message format 'Raw'. The expected message formats for the operation are 'Xml'; 'Json'. This can be because a WebContentTypeMapper has not been configured on the binding. See the documentation of WebContentTypeMapper for more details.'. See server logs for more details. The exception stack trace is:
Trying with AFNetworking:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = #{#"kat": #"0",#"oda": #"0", #"hastaAdi":hastaAdi, #"protokolNo":#"0",#"yatanAyaktan":#"1"};
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[manager POST:HASTAARAIP parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
But the log is like this:
Error: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x8e49ce0 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
ASI was long abandoned by the developer. using AFNetworking 2.0 will be more easy, and with a lot of good documentation: https://github.com/AFNetworking/AFNetworking
it looks like you are trying to make a #"POST" request.
you can use the following code snippet (uses IOS build in classes) to make the request:
NSDictionary *parameters = #{#"key" : value};
/* the following serialization is NOT a deep serialization */
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil];
NSURL *url = [NSURL URLWithString:#"http://www.someURL.com/whatEver"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0f];
[request setHTTPMethod:#"POST"];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSLog(#"all headers from response:%#", [httpResponse allHeaderFields]);
NSLog(#"status code from response:%ld", (long)[httpResponse statusCode]);
}
}];

Resources