redribben

calendarVC

Oct 26th, 2014
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. #import "CalendarViewController.h"
  3.  
  4.  
  5. @interface CalendarViewController ()
  6.  
  7.  
  8. @end
  9.  
  10. @implementation CalendarViewController {
  11.     NSMutableData* receivedData;
  12.     NSURLConnection *theConnection;
  13. }
  14. @synthesize scheduleImage;
  15.  
  16.  
  17.  
  18. - (void)viewDidLoad {
  19.     [super viewDidLoad];
  20. //    NSCache *memoryCache = [[NSCache alloc] init];
  21. //    [self secondAttempt];
  22. //    [self presentImage:[NSURL URLWithString:@"http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png"]];
  23.     [self fifthAttempt];
  24. //    [self displayImage];
  25.        // Do any additional setup after loading the view.
  26. }
  27.  
  28. - (void)didReceiveMemoryWarning {
  29.     [super didReceiveMemoryWarning];
  30.     // Dispose of any resources that can be recreated.
  31. }
  32.  
  33.  
  34. // To display the image straight from the URL
  35. // This displays an image, but it doesnt save it
  36. -(void)presentImage:(NSURL*)imageURL {
  37.     NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
  38.     UIImage *image = [UIImage imageWithData:imageData scale:2.0];
  39.     [self.scheduleImage setImage: image];
  40. }
  41.  
  42.  
  43.  
  44.  
  45. - (void) displayImage {
  46.     NSURL * imageURL = [NSURL fileURLWithPath:@"receivedData"];
  47.     NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
  48.     UIImage * image = [UIImage imageWithData:imageData];
  49.     [scheduleImage setImage:image];
  50. }
  51.  
  52.  
  53. - (void)secondAttempt {
  54.     NSCache *memoryCache = [[NSCache alloc] init]; //assume there is a memoryCache for images or videos
  55.    
  56.     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
  57.        
  58.         NSString *urlString = @"http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png";
  59.        
  60.         NSData *downloadedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
  61.        
  62.         if (downloadedData) {
  63.            
  64.             // STORE IN FILESYSTEM
  65.             NSString* cachesDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  66.             NSString *file = [cachesDirectory stringByAppendingPathComponent:urlString];
  67.             [downloadedData writeToFile:file atomically:YES];
  68.            
  69.             // STORE IN MEMORY
  70.             [memoryCache setObject:downloadedData forKey:@"downloadedPic"];
  71.         }
  72.        
  73.         // NOW YOU CAN CREATE AN AVASSET OR UIIMAGE FROM THE FILE OR DATA
  74.         NSURL *imageURL = [NSURL fileURLWithPath:@"downloadedPic"];
  75.         NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
  76.         UIImage *image = [UIImage imageWithData:imageData];
  77.         [scheduleImage setImage:image];
  78.         });
  79. }
  80.  
  81. /*
  82. #pragma mark - Navigation
  83.  
  84. // In a storyboard-based application, you will often want to do a little preparation before navigation
  85. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  86.     // Get the new view controller using [segue destinationViewController].
  87.     // Pass the selected object to the new view controller.
  88. }
  89. */
  90.  
  91.  
  92. #pragma from https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html#//apple_ref/doc/uid/20001836-BAJEAIEE
  93.  
  94. - (void)fifthAttempt {
  95.     // Create the request.
  96.     NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png"]
  97.                                               cachePolicy:NSURLRequestUseProtocolCachePolicy
  98.                                           timeoutInterval:60.0];
  99.    
  100.     // Create the NSMutableData to hold the received data.
  101.     // receivedData is an instance variable declared elsewhere.
  102.     receivedData = [NSMutableData dataWithCapacity: 0];
  103.    
  104.     // create the connection with the request
  105.     // and start loading the data
  106.     NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
  107.     if (!theConnection) {
  108.         // Release the receivedData object.
  109.         receivedData = nil;
  110.        
  111.         // Inform the user that the connection failed.
  112.     }
  113. }
  114.  
  115. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
  116. {
  117.     // Append the new data to receivedData.
  118.     // receivedData is an instance variable declared elsewhere.
  119.     [receivedData appendData:data];
  120. }
  121.  
  122.  
  123. - (void)connection:(NSURLConnection *)connection
  124.   didFailWithError:(NSError *)error
  125. {
  126.     // Release the connection and the data object
  127.     // by setting the properties (declared elsewhere)
  128.     // to nil.  Note that a real-world app usually
  129.     // requires the delegate to manage more than one
  130.     // connection at a time, so these lines would
  131.     // typically be replaced by code to iterate through
  132.     // whatever data structures you are using.
  133.     theConnection = nil;
  134.     receivedData = nil;
  135.    
  136.     // inform the user
  137.     NSLog(@"Connection failed! Error - %@ %@",
  138.           [error localizedDescription],
  139.           [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
  140. }
  141.  
  142. - (void)connectionDidFinishLoading:(NSURLConnection *)connection
  143. {
  144.     // do something with the data
  145.     // receivedData is declared as a property elsewhere
  146.     NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
  147.    
  148.     // Release the connection and the data object
  149.     // by setting the properties (declared elsewhere)
  150.     // to nil.  Note that a real-world app usually
  151.     // requires the delegate to manage more than one
  152.     // connection at a time, so these lines would
  153.     // typically be replaced by code to iterate through
  154.     // whatever data structures you are using.
  155.     theConnection = nil;
  156.     receivedData = nil;
  157. }
  158.  
  159.  
  160.  
  161.  
  162.  
  163.  
  164.  
  165.  
  166.  
  167.  
  168.  
  169.  
  170.  
  171. #pragma mark What I started off with
  172. - (void)doThisTask {
  173. // For this snippet we are downloading the same in two tasks.
  174. NSString *imageUrl = @"http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png";
  175. // You always start by creating an NSURLConfiguration.
  176. NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
  177. // This creates a session using the current class as a delegate.
  178. NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig
  179.                                                       delegate:self
  180.                                                  delegateQueue:nil];
  181. //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.
  182. NSURLSessionDownloadTask *getImageTask = [session downloadTaskWithURL:[NSURL URLWithString:imageUrl]
  183.                                                     completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
  184.                                                         // Here you use the location variable provided in the completion handler to get a pointer to the image
  185.                                                         UIImage *downloadedImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:location]];
  186.                                                         // Finally you could, for example, update UIImageView’s image to show the new file.
  187.                                                         dispatch_async(dispatch_get_main_queue(), ^{
  188.                                                             // do stuff with image
  189.                                                             _imageWithBlock.image = downloadedImage;
  190.                                                         });
  191.                                                     }];
  192.  
  193. // You always have to start up the task!
  194. [getImageTask resume];
  195. }
  196.  
  197.  
  198.  
  199. // if you needed to track the download progress, for either task creation method, you would need to use the following:
  200. -(void)URLSession:(NSURLSession *)session
  201.      downloadTask:(NSURLSessionDownloadTask *)downloadTask
  202.      didWriteData:(int64_t)bytesWritten
  203. totalBytesWritten:(int64_t)totalBytesWritten
  204. totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
  205. {
  206.     NSLog(@"%f / %f", (double)totalBytesWritten,
  207.           (double)totalBytesExpectedToWrite);
  208. }
  209.  
  210. @end
Advertisement
Add Comment
Please, Sign In to add comment