tags:

views:

68

answers:

2
NSURL * url = @"http://192.168.100.161/UploadWhiteB/wh.txt";
NSData * data = [NSData dataWithContentsOfURL:url];

if (data != nil) {
  NSLog(@"\nis not nil");
  NSString *readdata = [[NSString alloc] initWithContentsOfURL:(NSData *)data ];

I write this code to download a file from given url... but i get an error on line
NSData * data = [NSData dataWithContentsOfURL:url];

uncaught exception...

so please help me out.

A: 

-[NSString initWithContentsOfURL:] is deprecated. You should be using -[NSString (id)initWithContentsOfURL:encoding:error:]. In either case, the URL paramter is an NSURL instance, not an NSData instance. Of course you get an error trying to initialize a string with the wrong type. You can initialize the string with the URL data using -[NSString initWithData:encoding:], or just initialize the string directly from the URL.

Barry Wark
+1  A: 

Your first line should be

NSURL * url = [NSURL URLWithString:@"http://192.168.100.161/UploadWhiteB/wh.txt"];

(NSURL is not a string, but can easily be constructed from one.)

I'd expect you to get a compiler warning on your first line--ignoring compiler warnings is bad. The second line fails because dataWithContentsOfURL: expects to be given a pointer to an NSURL object and while you're passing it a pointer that you've typed NSURL*, url is actually pointing to an NSString object.

Isaac