3
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.

mjv
  • 73,152
  • 14
  • 113
  • 156
greshi gupta
  • 57
  • 1
  • 4

3 Answers3

4

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
  • 10,668
  • 5
  • 59
  • 68
  • Does the source of the `NSData` object matter for this method? [In this question](http://stackoverflow.com/questions/16150196/updating-sqlite-database-without-xml) I'm trying to download a .sqlite database into a `NSData` object from a URL, but it doesn't seem to be saving it correctly. The file is written, but when I try to access it (either through my app or with a 3rd party viewer) it tells me it's not a valid SQLite database. Does `dataWithContentsOfURL` only work for downloading .txt files or something like that? – GeneralMike Apr 25 '13 at 17:28
2
    NSString *file = @"http://192.168.100.161/UploadWhiteB/wh.txt";
    NSURL *fileURL = [NSURL URLWithString:file];

    NSLog(@"qqqqq.....%@",fileURL);

    NSData *fileData = [[NSData alloc] initWithContentsOfURL:fileURL];
Govind888
  • 21
  • 3
0

-[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
  • 107,306
  • 24
  • 181
  • 206