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}}}
Related
I am working on an application with xcode 9.2 and iOS 11.4 . When i try NSURLSession downloadTaskWithRequest in background and foreground switching of the application state some times the app get 200 success with Error Domain=NSURLErrorDomain Code=-1005 “The network connection was lost.”
The error is as follows :
NSLocalizedDescription = "The network connection was lost."; NSUnderlyingError = "Error Domain=kCFErrorDomainCFNetwork Code=-1005 \"(null)\" UserInfo={NSErrorPeerAddressKey={length = 28, capacity = 28, bytes = 0x1c1e01bb000000002604558000210000 ... a5c562bc00000000}, _kCFStreamErrorCodeKey=57, _kCFStreamErrorDomainKey=1}"; "_kCFStreamErrorCodeKey" = 57; "_kCFStreamErrorDomainKey" = 1;
My request is as follows :
NSMutableURLRequest *urlRequest = nil;
NSString *urlString = nil;
NSURL * url = nil;
urlString = [NSString stringWithFormat:#"https://%#%#", self.requestUrl, self.queueName];
url = [NSURL URLWithString:urlString];
urlRequest = [NSMutableURLRequest requestWithURL:url];
urlRequest.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
[urlRequest addValue:#"" forHTTPHeaderField:#"User-Agent";
[urlRequest setHTTPMethod:#"DELETE"];
[urlRequest setTimeoutInterval:REQUEST_TIMEOUT];
[urlRequest addValue:#"correlID, msgId, usr-clientMessageId" forHTTPHeaderField:#"x-msg-require-headers"];
[urlRequest addValue:self.messageInfo.messageId forHTTPHeaderField:#"x-msg-msgId"];
[urlRequest addValue:#"Delivery" forHTTPHeaderField:#"applicationOrgin"];
[urlRequest addValue:#"" forHTTPHeaderField: #"x-msg-wait";
And the downloadTaskWithRequest code snippet is as follows :
self.downloadTask = [self.urlSession downloadTaskWithRequest:urlRequest completionHandler:
^(NSURL *location, NSURLResponse *response, NSError *error){
FLog(#"received response for message type: %d and operation type: %d\n",self.messageType, self.requestType);
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
FLog(#"%ld for operation %d for request type %d",(long)[httpResponse statusCode],self.self.messageType,self.requestType);
FLog(#"response is %#",response);
NSHTTPURLResponse *httpresp = (NSHTTPURLResponse *)response;
NSString * origId = [[httpresp allHeaderFields] objectForKey:(#"x-msg-msgId")];
FLog(#"recieved response header %#",httpresp.allHeaderFields);
[self downloadCompletedWithResponse:response location:location error:error];
}];
[self.downloadTask resume];
Is anybody facing the same issue? Could any body having idea to resolve this issue
I am having an issue in making a call to our RESTful API. The request is to get the token from the API; I need that token to use it to make further calls on that API.
The issue is that whenever I make that call, I get HTTP 403 status code and I don't know why. I am making the same calls from Android but they work fine without any issue.
Actually I have no experience at all to work with xCode; I am just implementing some changes in the existing code which was written by some other developer. I don't know if I am doing something wrong or what.
id keys[] = {#"grant_type", #"client_id", #"client_secret", #"username", #"password"};
id objects[] = {#"password", #"AppClientID", #"AppClientSecret", #"usernamehere", #"userpasswordhere"};
NSUInteger count = sizeof(objects) / sizeof(id);
NSDictionary *d = [NSDictionary dictionaryWithObjects:objects forKeys:keys count:count];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:d options:NSJSONWritingPrettyPrinted error:nil];
NSURL *url = [NSURL URLWithString:#"https://oauth-test.websitename.com/token"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"Basic" forHTTPHeaderField:#"Authorization"];
[request setHTTPBody:jsonData];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError) {
if(data.length > 0 && connectionError == nil) {
NSLog(#"Response --> %# ", response);
}
}
];
Can someone try to help me figure out what is actually going wrong?
Thanks in advance.
I ran your code and the log, i am getting is
Error Domain=NSURLErrorDomain Code=-1003 "A server with the specified
hostname could not be found." UserInfo=
{NSUnderlyingError=0x608000059aa0 {Error Domain=kCFErrorDomainCFNetwork
Code=-1003 "A server with the specified hostname could not be found."
UserInfo={NSErrorFailingURLStringKey=http://oauth-
test.websitename.com/token, NSErrorFailingURLKey=http://oauth-
test.websitename.com/token, _kCFStreamErrorCodeKey=8,
_kCFStreamErrorDomainKey=12, NSLocalizedDescription=A server with the
specified hostname could not be found.}},
NSErrorFailingURLStringKey=http://oauth-test.websitename.com/token,
NSErrorFailingURLKey=http://oauth-test.websitename.com/token,
_kCFStreamErrorDomainKey=12, _kCFStreamErrorCodeKey=8,
NSLocalizedDescription=A server with the specified hostname could not
be found.}
I tried it with NSUrlSession also but it is giving same problem.
I think your server is not configured
Below is the code with URL session
id keys[] = {#"grant_type", #"client_id", #"client_secret",
#"username", #"password"}; id objects[] = {#"password", #"AppClientID", #"AppClientSecret", #"usernamehere", #"userpasswordhere"};
NSUInteger count = sizeof(objects) / sizeof(id); NSDictionary *d = [NSDictionary dictionaryWithObjects:objects forKeys:keys count:count];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:d options:NSJSONWritingPrettyPrinted error:nil];
NSURL *url = [NSURL URLWithString:#"http://oauth-test.websitename.com/token"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"Basic" forHTTPHeaderField:#"Authorization"]; [request setHTTPBody:jsonData];
NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionDownloadTask *dataTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(#"%#", response);
}];
[dataTask resume];
Hi I am trying to Http PUT method in NSURLConnection.
I am posting data file to an amazon s3 path.
-(void)postFaceVideo{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://face_video.s3.amazonaws.com/chunks/?AWSAccessKeyId=MYKEY&Expires=1424373411&Signature=MYSIGNATURE"]];
[request setHTTPMethod:#"PUT"];
[request setHTTPBody:appDelegate.faceData]; // This is the saved NSData
[request setTimeoutInterval:200];
conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) {
webData = [NSMutableData data];
}
}
Before it was working fine, but now neither data is posted in the server nor any response is coming. What could be the reason?
Is there any change in these method in Xcode 6, because previously it worked fine when I was working with Xcode 5.
Also I have tried with NSURLSession as follows.
-(void)postFaceVideo2{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://face_video.s3.amazonaws.com/chunks/?AWSAccessKeyId=MYKEY&Expires=1424373411&Signature=MYSIGNATURE"]];
[request setValue:[NSString stringWithFormat:#"%d",appDelegate.faceData.length] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
request.HTTPMethod = #"PUT";
request.HTTPBody = appDelegate.faceData;
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response, NSError *error)
{
if (!error)
{
NSLog(#"Status code: %i", ((NSHTTPURLResponse *)response).statusCode);
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ;
}
else
{
NSLog(#"Error: %#", error.localizedDescription);
NSLog(#"Error: %#", error.description);
}
}];
[task resume];
}
Here I am getting the error as -
Error: Error Domain=NSURLErrorDomain Code=-1001 "The operation couldn’t be completed. (NSURLErrorDomain error -1001.)" UserInfo=0x171cadb0 {NSErrorFailingURLKey=https://video_test.s3.amazonaws.com/chunks_dev/21662/facescan_1?Signature= MYSIGN =&Expires=1424381789&AWSAccessKeyId=MYID, NSErrorFailingURLStringKey=https://video_test.s3.amazonaws.com/chunks_dev/21662/facescan_1?Signature=MYSIGN=&Expires=1424381789&AWSAccessKeyId=MYID, NSUnderlyingError=0x171b30c0 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1001.)"}
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.)"}
First of i want to tell you its a duplicate question, but i have tried all the ways possible
- link I have searched--> Bad URL when requesting with NSURL
iOS Develoment: Why is my NSURLConnection failing with a "bad URL" error for only some users?
Bad URL when requesting with NSURL
I am sending a request to server-> but am always getting bad URL error i.e
Request Failed with Error: Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0xcbf0680 {NSUnderlyingError=0xc9ad8e0 "bad URL", NSLocalizedDescription=bad URL}, {
NSLocalizedDescription = "bad URL";
NSUnderlyingError = "Error Domain=kCFErrorDomainCFNetwork Code=-1000 \"bad URL\" UserInfo=0xc96dc30 {NSLocalizedDescription=bad URL}";
}
Code->
NSString *imgUrl = [NSString stringWithFormat:#"https://graph.facebook.com/%#/picture", fbid];
NSString *urlString = [NSString stringWithFormat:#"%#url=register_user.json&username=%#&email=%#&dob=%#&by_socialnetwork=\"1\"&gender=%#&nicename=%#&socialimageurl=%#",BASE_URL,[info_dict objectForKey:#"username"],[info_dict objectForKey:#"email"],[info_dict objectForKey:#"birthday"],[info_dict objectForKey:#"gender"],[info_dict objectForKey:#"name"],imgUrl];
NSLog(#"url %#",urlString );
[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
[request setHTTPMethod:#"GET"];
[request addValue:#"text/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
//NSURLRequest *request=[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
NSLog(#"url %#",request );
AFJSONRequestOperation *operation=[AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"dgj,gfj,gf,j%#",JSON);
[self requestSucceedWithItems:JSON forRequestType:#"FB"];
}failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
[appdelegate showAlert:#"Error" forText:#"Network activity failed,Try later."];
}];
[operation start];
terminal NSLOG Response:-
url <NSURLRequest: 0xcd8d060> { URL: http://192.168.1.100/~ha/gokk/index.php?url=register_user.json&username=abx&email=abxx#gmail.com&dob=12/19/1978&by_socialnetwork=1&gender=male&nicename=Sam&socialimageurl=https://graph.facebook.com/1008823838/picture }
Response:-
****Sometime i am getting BAD url Error or this ****
2014-02-06 13:37:01.426 Flokk[1561:a0b] Request Failed with 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=0xc953c20 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}, {
NSDebugDescription = "JSON text did not start with array or object and option to allow fragments not set.";
}