How to download file from particular url?

2020-07-22 10:13发布

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.

标签: objective-c
3条回答
虎瘦雄心在
2楼-- · 2020-07-22 10:39

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.

查看更多
SAY GOODBYE
3楼-- · 2020-07-22 10:45
    NSString *file = @"http://192.168.100.161/UploadWhiteB/wh.txt";
    NSURL *fileURL = [NSURL URLWithString:file];

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

    NSData *fileData = [[NSData alloc] initWithContentsOfURL:fileURL];
查看更多
相关推荐>>
4楼-- · 2020-07-22 10:50

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

查看更多
登录 后发表回答