OC中下载网络图片到本地


#import


int main(int argc, const char * argv[]) {

    @autoreleasepool {

        // insert code here...

//https://www.baidu.com/img/bd_logo1.png

//        NSURL *url = [NSURL URLWithString:@"https://www.baidu.com/img/bd_logo1.png"];

//http://www.xinhuanet.com/photo/2018-03/13/1122528717_15209051820841n.jpg

        NSURL *url = [NSURL URLWithString:@"http://www.xinhuanet.com/photo/2018-03/13/1122528717_15209051820841n.jpg"];

        NSURLRequest *request = [NSURLRequest requestWithURL:url];

        NSError *err;

        //save the data in binary

        

        NSData *data = [NSURLConnection sendSynchronousRequest:request

                                             returningResponse:NULL

                                                         error:&err];

        

        

        if(!data) {

            NSLog(@"Fetch failed : %@", [err localizedDescription]);

        }

        NSLog(@"The file is %lu bytes", (unsigned long)[data length]);

        

        BOOL written = [data writeToFile:@"/Users/demi/Ming/test/renda.jpg" options:0 error:&err];

        

        if(!written) {

            NSLog(@"Write failed : %@", [err localizedDescription]);

        }

        NSLog(@"Success");

        

    }

    return 0;

}

Result:

2018-03-13 21:27:13.703527+0800 TOCSaveNSDataa[64376:3910850] The file is 137361 bytes

2018-03-13 21:27:13.719984+0800 TOCSaveNSDataa[64376:3910850] Success

Program ended with exit code: 0


你可能感兴趣的:(OC)