How to download a file from a specific URL?

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 am writing this code to download a file from a given url ... but I get an error on the line
NSData * data = [NSData dataWithContentsOfURL:url];

uncaught exception ...

please help me.

+3
source share
3 answers

Your first line should be

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

( NSURLNot a string, but can be easily built from one.)

I expect you to get a compiler warning in your first line - ignoring compiler warnings is bad. The second line fails because it dataWithContentsOfURL:expects there will be a pointer to an object NSURL, and while you pass it the pointer that you typed NSURL*, urlit actually points to the object NSString.

+4
    NSString *file = @"http://192.168.100.161/UploadWhiteB/wh.txt";
    NSURL *fileURL = [NSURL URLWithString:file];

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

    NSData *fileData = [[NSData alloc] initWithContentsOfURL:fileURL];
+2

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

0
source

Source: https://habr.com/ru/post/1742406/


All Articles