WYS
WYS

Reputation: 1647

Webserver NSURL NSURLConnection

Ok, I'm trying to get a file from my webserver. But I'm getting kinda confused about some stuff. When I use NSURL I can get my xml-file with an url like this: "localhost...../bla.xml". But I'm also trying to test some things... Like... What will happen to my app if I have an open connection to the webserver, and I lose connection to internet? The above method with the NSURL, I haven't really established any connection where it always is connected right? or should I use be using NSURLConnection?

Maybe it's a little confusing, because I'm confused. I hope someone can give me some info I can research about.

Thanks.

Upvotes: 0

Views: 239

Answers (2)

0x8badf00d
0x8badf00d

Reputation: 6391

Take a look at NSURLConnection Class. http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html

Create connection object and set a timeout value, if you lose the connection or the connection times out NSURLConnection delegate method: - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error gets called and you would be notified of that event.

You might also use NSURLConnection sendSynchronousRequest method, but its strongly discouraged to use that method as it would block the thread its running.

Upvotes: 3

dylanweber
dylanweber

Reputation: 608

Are you trying to access the content of a file? If so, you would use the following.

NSError *error;
NSURL *url = [NSURL URLwithString:@"localhost/file.html"];
NSString *filecontents = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];

The NSString object filecontents would contain your string.

You wouldn't be able to loose connection in such a short time. If there is no connection, an error would be applied to error.

EDIT: If you wanted to constantly stay connected to a server, that is a different story. You have have to use C's send() and recv() functions, which you can read about here. I don't know much about it, and I'm learning it myself, so you should ask someone else on how to set up a server. But you will need to have another program running simultaniously.

Upvotes: 0

Related Questions