Nsurlconnection Get Request Returns -1005, "The Network Connection Was Lost"

NSURLConnection is run many times

I assume what you're concerned about is the overhead of creating the HTTP connection. NSURLConnection is smart enough to handle this for you using HTTP/1.1 and reusing existing connections. It does not use pipelining last time I checked, but for your purpose, connection reuse should be sufficient. I do encourage you to put a network sniffer on this and make sure that it's working as you want them to.

The cost of creating the objects themselves is trivial on the order of once per 5s and you shouldn't try to optimize that (though of course you should reuse the NSURL). It's the opening a connection to the server that's expensive, especially on iPhone.

If you find you really do need pipelining, you unfortunately will have to roll your own. I've heard that CFHTTPStream can do it, but I don't see a lot of evidence of that. CocoaAsyncSocket is your best bet for low-level access to the sockets without having to write low-level code.

Since latency on the cell network can be very bad, it's possible that your connection will take longer than 5s to complete. Do make sure that one connection is done before starting the next, or you'll start making more and more open connections.

NSURLconnection fails on 3g 'network connection was lost'

I would start putting NSLog's in the delegate methods. Start with didReceiveData.

 -(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) receiveddata          { 
if (receiveddata != nil){
[XMLData appendData:receiveddata];
NSLog(@"didReceiveData :receiveddata is:%@", receiveddata);

}
else{
NSLog(@"NO Data:%@");
}

}

error handling with NSURLConnection sendSynchronousRequest

-sendSynchronousRequest:returningResponse:error: gives you a way to get an error right there in the method itself. That last argument is really (NSError **) error; that is, a pointer to an NSError pointer. Try this:

NSError        *error = nil;
NSURLResponse *response = nil;

[NSURLConnection sendSynchronousRequest: req returningResponse: &response error: &error];

if (error) {...handle the error}

NSURLConnection automatic direct connection if proxy.pac download fails

I figured it out. It had to do with the request timeout interval. The default timeout interval for NSURLRequest is 60 seconds. It was taking almost 90 seconds for the initial proxy timeout to occur so NSURLConnection wasn't falling back to the direct connection. Once I increased the timeout in the request, it started working.

NSURLConnection does not call complete across multiple Views

I've figured it out. In my second view (where i w8 for the operation complete) I cannot w8 using ThreadSleep! I have to use [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];

Handling redirects correctly with NSURLConnection

There's a note in section 10.3.2 of RFC 2616 about this behaviour:

Note: When automatically redirecting a POST request after
receiving a 301 status code, some existing HTTP/1.0 user agents
will erroneously change it into a GET request.

So this behaviour seems to be non-standard but historical. That GET request is not a POST, and it'll be missing the payload.

Interestingly enough, this is also in the same section:

If the 301 status code is received in response to a request other
than GET or HEAD, the user agent MUST NOT automatically redirect the
request unless it can be confirmed by the user, since this might
change the conditions under which the request was issued.

That's pretty clear and seems to indicate we can't fix this, but I think ignoring this for the purpose of our own web service clients for services we pick (or control) is probably the least bad alternative.

So how do we solve this?

Instead of the willSendResponse: in the original question, I'm using this:

- (NSURLRequest *)connection: (NSURLConnection *)connection
willSendRequest: (NSURLRequest *)request
redirectResponse: (NSURLResponse *)redirectResponse;
{
if (redirectResponse) {
// we don't use the new request built for us, except for the URL
NSURL *newURL = [request URL];
// Previously, store the original request in _originalRequest.
// We rely on that here!
NSMutableURLRequest *newRequest = [_originalRequest mutableCopy];
[newRequest setURL: newURL];
return newRequest;
} else {
return request;
}
}

The idea here is that instead of cloning the new request and trying to shape it the same as the one Cocoa Touch sends me, I create a clone of the original request and change just the URL to match the request Cocoa Touch sent me. That original request is still a POST with the payload attached.

If you control the server, it's worth reading RFC 2616, section 10.3 in its entirety to see if there's a better code you can use (while checking, of course, that iOS handles the better code as it should).

You could also make a mutable copy of the redirected request and replace its HTTP method with the HTTP method of the original request. Same general principle, though that would favour keeping things from the new request rather than the old. In some circumstances that might work better, but I haven't tested this yet.

How to manage multiple asynchronous NSURLConnection request

use just like

  NSURLConnection *itemIdConnection,*contactNameConnection;
NSMutableData *receivedData, *locationData;

and your delegate method is

 #pragma NSUrlConnectionDelegate Methods

-(void)connection:(NSConnection*)conn didReceiveResponse:(NSURLResponse *)response
{

if(connection == itemIdConnection)
{
if (receivedData == NULL)
{
receivedData = [[NSMutableData alloc] init];
}
[receivedData setLength:0];
}

if(connection == contactNameConnection)
{
if (locationData == NULL)
{
locationData = [[NSMutableData alloc] init];
}

[locationData setLength:0];
}



}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{

if (connection==itemIdConnection) {
[receivedData appendData:data];
}
if(connection == contactNameConnection)
{
[locationData appendData:data];
}

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"Connection failed! Error - %@ %@",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
UIAlertView *customAlert = [[UIAlertView alloc]initWithTitle:@"No NetWork" message:@"Interet Connection is Lost" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
[customAlert show];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{


if (connection==itemIdConnection) {
// NSError *e = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:receivedData options: kNilOptions error:nil];
NSString *tmp=[[NSString alloc]initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(@"%@", tmp);
NSLog(@" parsing JSON: %@", jsonDict);


}

if (connection==contactNameConnection) {
NSError *e = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:locationData options: NSJSONReadingMutableContainers error: &e];
NSLog(@" parsing JSON: %@", jsonDict);
}



}


Related Topics



Leave a reply



Submit