I am trying to connect to some local network of mine (hardware ).
So i find the network on the iPhone settings, and connect to it .
Now , i am trying to send a simple request to that access point .
The access point does getting my request, and send back respond, problem is, i never get the respond on the device.
If i try to send the request using Chrome browser on my mac , i do get the respond "hello world" , but not on the device.
I have tried synchronise and un-synchronise requests, non of which give me nothing. they do although send the request . what am i missing ?
sync:
NSURLRequest * urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://192.168.x.x/data:moredata"]];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * tdata = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
NSLog(#"-%#",tdata);
and async, delegates are not being called :(did register for them with <NSURLConnectionDelegate )
NSMutableURLRequest *request = [ [NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:#"http://192.168.x.x/data:datax"]];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO ];
[conn scheduleInRunLoop:[NSRunLoop mainRunLoop]
forMode:NSDefaultRunLoopMode];
[conn start];
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"+%#",response);
_responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"-%#",data);
[_responseData appendData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"DO");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"FAILEDERR");
}
Related
I have to do SSL pinning so need to verify server side SSL certificate.
SO I have to use NSURL delegates. I have a helper class in which I have created method which returns me login response:
- (NSData *)sendSynchronousRequest:(NSString *)strNewLoginRequest
returningResponse:(NSURLResponse **)response
error:(NSError **)error {
NSMutableURLRequest *finalRequest = nil;
NSURL *url= [NSURL URLWithString:const_url];
finalRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0];
NSData *requestData = [NSData dataWithBytes:[strLoginRequest UTF8String] length:[strLoginRequest length]];
self.connection = [[NSURLConnection alloc] initWithRequest:finalRequest delegate:self startImmediately:NO];
NSRunLoop *currentRunLoop = [NSRunLoop currentRunLoop];
[self.connection unscheduleFromRunLoop:currentRunLoop forMode:NSDefaultRunLoopMode];
[self.connection scheduleInRunLoop:currentRunLoop forMode:#"connectionRunLoopMode"];
[self.connection start];
while ([currentRunLoop runMode:#"connectionRunLoopMode" beforeDate:[NSDate distantFuture]]);
return self.mutableResponse;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.response = response;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
self.mutableResponse = [[NSMutableData alloc]init];
[self.mutableResponse appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
dispatch_async(dispatch_get_main_queue(), ^{
if (loadingView)
{
[loadingView removeView];
}
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Failure" message:#"Network Failure" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
});
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (loadingView)
{
[loadingView removeView];
}
self.resultString = [[NSString alloc] initWithData:self.mutableResponse encoding:NSASCIIStringEncoding];
}
and I am calling this method from another class called ViewController with code
-(void)doLogin
{
self.service = [[SyncCommunicationService alloc]init];
NSData *data = [self.service sendSynchronousRequest:strNewLoginRequest
returningResponse:&response
error:nil];
}
I have tried calling this method in background and on main thread but still delegate methods are not getting called, I have tried many other answers from same website but still couldn't able to solve this issue so please can anybody have a clue what am I doing wrong.
I'm wondering why would anyone use asynchronous request for performing task synchronously? Not to mention this strange way to wait with while statement instead of dispatch_semaphore or something similar.
However, why You even bother with delegate? Just use class method sendSynchronousRequest:returningResponse:error:. I think, it would suffice in your case
I am looking for a sample to send and receive http GET request in iOS. All I want to
do is handle communication in background thread such that it does not block main thread
and also want to handle http standard error code. Can anyone suggest me reference code or
example to handle http response data and handle proper memory management?
Any help will be thankful.
Two methods to achieve it:
1) NSURLCOnnection sendAsynchronousRequest method:
NSString *strURL= [NSString stringWithFormat:#"http://www.google.com/"];
NSURL *URL = [NSURL URLWithString:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *requestURL = [[NSURLRequest alloc] initWithURL:URL];
[NSURLConnection sendAsynchronousRequest:requestURL
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSLog(#"Response is:%#",[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
}];
2) Create and fire request then NSURLConnection Delegate Methods to get the response:
// Create the request.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://google.com"]];
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
#pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// A response has been received, this is where we initialize the instance var you created
// so that we can append data to it in the didReceiveData method
// Furthermore, this method is called each time there is a redirect so reinitializing it
// also serves to clear it
_responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
[_responseData appendData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
// Return nil to indicate not necessary to store a cached response for this connection
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// The request has failed for some reason!
// Check the error var
}
When I'm using NSURLConnection to get data from my server, iOS still cache data. When requesting new data, iOS sending a new request to my server, but the files are still stored.
I'm using NSURLRequestReloadIgnoringCacheData and returning nil in connection:willCacheResponse:.
The problem is that I'm using my own caching object, and it's kind of dum to let iOS store a duplicate.
Should I ignore this or should I delete the cache somehow?
Update
Code for creating NSURLRequest:
request = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0];
Code for creating NSURLConnection:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
Code for NSURlConnectionDelegate:
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
return nil;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[recivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
if (_handler) _handler(response, error, nil);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if (_handler) _handler(response, nil, recivedData);
recivedData = nil;
response = nil;
}
I'm sending to my server user detail and it is supposed to return a user id as a string,
the data received at my server bat I can get the string.
The code:
NSString *urlStr = [NSString stringWithFormat:#"url/////api/%#/%#",
[Email.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[Password.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
nil];
NSString *content = #"field1=42&field2=Hello";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlStr]];
[request setHTTPMethod:#"GET"];
[request setHTTPBody:[content dataUsingEncoding:NSISOLatin1StringEncoding]];
[NSURLConnection connectionWithRequest:request delegate:self];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
NSLog(#"good conection");
[_receivedData appendData:_data];
NSString *DataString = [[NSString alloc] initWithData:_receivedData encoding:NSUTF8StringEncoding];
NSLog(#"foo1: %#", DataString);
NSLog(#"foo2: %#", _receivedData);
}
2014-01-03 22:27:57.322 App[962:70b] foo1:
2014-01-03 22:27:57.323 App[962:70b] foo2: (null)
Implement following NSURLConnection delegate to fetch data asynchronously.
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// A response has been received, this is where we initialize the instance var you created
// so that we can append data to it in the didReceiveData method
// Furthermore, this method is called each time there is a redirect so reinitializing it
// also serves to clear it
_responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
[_responseData appendData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
// Return nil to indicate not necessary to store a cached response for this connection
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// The request has failed for some reason!
}
So in my application I use a NSURLConnection to connect to a server and retrieve text. This is how I initiate my NSURLConnection:
NSMutableURLRequest * serviceRequest = [NSMutableURLRequest requestWithURL:postUrl cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];
//Some other code
[serviceRequest setValue:contentType forHTTPHeaderField:#"Content-Type"];
[serviceRequest setHTTPMethod:#"POST"];
[serviceRequest setHTTPBody:postData];
//Force to return size
[serviceRequest setValue:#"" forHTTPHeaderField:#"Accept-Encoding"];
theConnection = [[NSURLConnection alloc] initWithRequest:serviceRequest delegate:self];
Now it works fine but I am trying to get a progress bar in my application to represent the progress of this request.
Now here are my didReceiveResponse and didReceiveData methods:
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
dlSize = [response expectedContentLength];
NSLog(#"didReceiveResponse: %f", dlSize);
[self.receivedData setLength:0];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
dlProgress = ((float) [data length] / (float) dlSize);
NSLog(#"dlProgress: %f", dlProgress);
}
So this is the issue. As you can see I have two NSLogs in there, but they are not called until the request is done. To be specific I am contacting a server to OCR something and once it is done OCRing and I get the text, that is when these two methods are called. Then the logs return something like this:
2013-07-30 22:50:09.201 app[39381:907] didReceiveResponse: 514.000000
2013-07-30 22:50:09.202 app[39381:907] dlProgress: 1.000000
2013-07-30 22:54:39.651 app[39381:907] didReceiveResponse: 305.000000
2013-07-30 22:54:39.651 app[39381:907] dlProgress: 1.000000
I am not sure why those methods aren't called during the request but maybe somebody on this site knows why? Anyway any tips/comments/suggestions are appreciated so I can get a UIProgressView hooked up with this.
Thanks!
declare in yourViewController.h NSURLResponse *response;
in this method write only:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)aResponse
{
response = aResponse;
}
after (downData is a NSMUtableData)(progresso is UIProgressView):
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[downData appendData:data];
float expectedLength = [response expectedContentLength];
float currentLength = downData.length;
progresso.progress = currentLength / expectedLength;
if (currentLength/expectedLength == 1) {
//do anything
}
}