NSURLConnection deprecated?


#1

Hello everyone,

I am a new programmer and trying to learn through this book, but am stuck trying to use NSURLSession to work around the problem that NSURLConnection has been deprecated. Anyone get a nice work around for this section of the book (page 201)?


#2

An answer to my own question. Had Xcode run deployment info for 10.10 and can use the code in book as written. Helping me understand things better, sorry to bother people with such a trivial question.


#3

It’s my solving of downloading file and saving with NSData:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        // Download file from URL and saving one to file system
        NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
        
        NSString *urlAddress = @"http://www.google.com/images/logos/ps_logo2.png";
        NSURL *url = [NSURL URLWithString:urlAddress];
        NSLog(@"Download image");

         NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            NSLog(@"The file is %lu bytes", (unsigned long)[data length]);

            BOOL written = [data writeToFile:@"/tmp/google.png" options:0 error:&error];

            if (written) {
                NSLog(@"Success");
            } else {
                NSLog(@"In completionHandler: %@ error: %@", response, error);
                NSLog(@"write failed: %@", [error localizedDescription]);
            }
             
             // Read downoaded file from file system
             error = nil;
             NSData *readData = [[NSData alloc] initWithContentsOfFile:@"/tmp/google.png"
                                                               options:1 error:&error];
             if (!readData) {
                 NSLog(@"read failed: %@", [error localizedDescription]);
             } else {
                 NSLog(@"The file read from the disk has %lu bytes", (unsigned long)[readData length]);
             }
        }];
        
        [task resume];
        [runLoop run];
    }

    return 0;
}