4 Replies Latest reply: Aug 14, 2008 10:21 AM by BPerfetto
BPerfetto Level 1 Level 1 (0 points)
Hi!

I'm currently using the following code to interface with a PHP server and get responses:


NSData* myData = [NSData dataWithContentsOfURL: [NSURL URLWithString:myURL]];


This works great and myData returns either nil or the response from the server. The only problem is that if the connection is very weak or slow then my program is stuck until this line of code returns. Is there a way to set the timeout interval for this call?

Thanks!

Mac Mini, Mac OS X (10.5.2)
  • Marcon Level 1 Level 1 (0 points)
    BPerfetto,

    Are you using the dataWithContentsOfURL to place data in a UITextView control? If so, can you share on how you are passing the myData value to the UITextView control?

    Thank you
  • Chuck Tee Level 1 Level 1 (80 points)
    For setting a timeout, maybe try using NSMutableURLRequest

    Since you're apparently communicating with a PHP server and (I assume) sending information to a service, this method works great when you need to mess around with headers, etc.


    ...Init stuff...

    NSMutableURLRequest *theRequest=[NSMutableURLRequest
    requestWithURL:[NSURL URLWithString:theServerURL]
    cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];

    [theRequest setHTTPMethod:@"POST"];
    [theRequest setValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [theRequest setValue:myContentLength forHTTPHeaderField:@"Content-length"];

    [theRequest setHTTPBody:[XMLString dataUsingEncoding:NSUTF8StringEncoding]];

    serverData = [NSURLConnection sendSynchronousRequest:theRequest
    returningResponse:serverResponse error:myError];

    NSString *serverDataString = [[[NSString alloc] initWithData:serverData
    encoding:NSUTF8StringEncoding] retain];

    NSLog(@"Data: %@",serverDataString);
    ...



    The code snippet doesn't have all the init stuff, but you should be able to get a start.

    Message was edited by: Chuck Tee
  • BPerfetto Level 1 Level 1 (0 points)
    Thanks, guys!

    I ended up using a seperate thread for my [NSData] call and that worked great!

    Marcopio, the return from initWithContentsOfURL is just the straight ASCII response from the server. So I simply parse it for the information I need and then use that.

    Hope that helps!