Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #import "CalendarViewController.h"
- @interface CalendarViewController ()
- @end
- @implementation CalendarViewController {
- NSMutableData* receivedData;
- NSURLConnection *theConnection;
- }
- @synthesize scheduleImage;
- - (void)viewDidLoad {
- [super viewDidLoad];
- // NSCache *memoryCache = [[NSCache alloc] init];
- // [self secondAttempt];
- // [self presentImage:[NSURL URLWithString:@"http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png"]];
- [self fifthAttempt];
- // [self displayImage];
- // Do any additional setup after loading the view.
- }
- - (void)didReceiveMemoryWarning {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- }
- // To display the image straight from the URL
- // This displays an image, but it doesnt save it
- -(void)presentImage:(NSURL*)imageURL {
- NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
- UIImage *image = [UIImage imageWithData:imageData scale:2.0];
- [self.scheduleImage setImage: image];
- }
- - (void) displayImage {
- NSURL * imageURL = [NSURL fileURLWithPath:@"receivedData"];
- NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
- UIImage * image = [UIImage imageWithData:imageData];
- [scheduleImage setImage:image];
- }
- - (void)secondAttempt {
- NSCache *memoryCache = [[NSCache alloc] init]; //assume there is a memoryCache for images or videos
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
- NSString *urlString = @"http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png";
- NSData *downloadedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
- if (downloadedData) {
- // STORE IN FILESYSTEM
- NSString* cachesDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
- NSString *file = [cachesDirectory stringByAppendingPathComponent:urlString];
- [downloadedData writeToFile:file atomically:YES];
- // STORE IN MEMORY
- [memoryCache setObject:downloadedData forKey:@"downloadedPic"];
- }
- // NOW YOU CAN CREATE AN AVASSET OR UIIMAGE FROM THE FILE OR DATA
- NSURL *imageURL = [NSURL fileURLWithPath:@"downloadedPic"];
- NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
- UIImage *image = [UIImage imageWithData:imageData];
- [scheduleImage setImage:image];
- });
- }
- /*
- #pragma mark - Navigation
- // In a storyboard-based application, you will often want to do a little preparation before navigation
- - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
- // Get the new view controller using [segue destinationViewController].
- // Pass the selected object to the new view controller.
- }
- */
- #pragma from https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html#//apple_ref/doc/uid/20001836-BAJEAIEE
- - (void)fifthAttempt {
- // Create the request.
- NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png"]
- cachePolicy:NSURLRequestUseProtocolCachePolicy
- timeoutInterval:60.0];
- // Create the NSMutableData to hold the received data.
- // receivedData is an instance variable declared elsewhere.
- receivedData = [NSMutableData dataWithCapacity: 0];
- // create the connection with the request
- // and start loading the data
- NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
- if (!theConnection) {
- // Release the receivedData object.
- receivedData = nil;
- // Inform the user that the connection failed.
- }
- }
- - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
- {
- // Append the new data to receivedData.
- // receivedData is an instance variable declared elsewhere.
- [receivedData appendData:data];
- }
- - (void)connection:(NSURLConnection *)connection
- didFailWithError:(NSError *)error
- {
- // Release the connection and the data object
- // by setting the properties (declared elsewhere)
- // to nil. Note that a real-world app usually
- // requires the delegate to manage more than one
- // connection at a time, so these lines would
- // typically be replaced by code to iterate through
- // whatever data structures you are using.
- theConnection = nil;
- receivedData = nil;
- // inform the user
- NSLog(@"Connection failed! Error - %@ %@",
- [error localizedDescription],
- [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
- }
- - (void)connectionDidFinishLoading:(NSURLConnection *)connection
- {
- // do something with the data
- // receivedData is declared as a property elsewhere
- NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
- // Release the connection and the data object
- // by setting the properties (declared elsewhere)
- // to nil. Note that a real-world app usually
- // requires the delegate to manage more than one
- // connection at a time, so these lines would
- // typically be replaced by code to iterate through
- // whatever data structures you are using.
- theConnection = nil;
- receivedData = nil;
- }
- #pragma mark What I started off with
- - (void)doThisTask {
- // For this snippet we are downloading the same in two tasks.
- NSString *imageUrl = @"http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png";
- // You always start by creating an NSURLConfiguration.
- NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
- // This creates a session using the current class as a delegate.
- NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig
- delegate:self
- delegateQueue:nil];
- //Tasks are always created by sessions. This one is created with the block-based method. Remember you could still use the NSURLSessionDownloadDelegate to track download progress.
- NSURLSessionDownloadTask *getImageTask = [session downloadTaskWithURL:[NSURL URLWithString:imageUrl]
- completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
- // Here you use the location variable provided in the completion handler to get a pointer to the image
- UIImage *downloadedImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:location]];
- // Finally you could, for example, update UIImageView’s image to show the new file.
- dispatch_async(dispatch_get_main_queue(), ^{
- // do stuff with image
- _imageWithBlock.image = downloadedImage;
- });
- }];
- // You always have to start up the task!
- [getImageTask resume];
- }
- // if you needed to track the download progress, for either task creation method, you would need to use the following:
- -(void)URLSession:(NSURLSession *)session
- downloadTask:(NSURLSessionDownloadTask *)downloadTask
- didWriteData:(int64_t)bytesWritten
- totalBytesWritten:(int64_t)totalBytesWritten
- totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
- {
- NSLog(@"%f / %f", (double)totalBytesWritten,
- (double)totalBytesExpectedToWrite);
- }
- @end
Advertisement
Add Comment
Please, Sign In to add comment