redribben

BMDirectorySetUp.m

Oct 30th, 2014
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #import "BMDirectorySetUp.h"
  2.  
  3. @interface BMDirectorySetUp ()
  4.  
  5. @property (copy, nonatomic) NSString *downloadedImageOnDevice;
  6. @property (copy, nonatomic) NSString *currentImageOnServer;
  7. @property int numberOfImagesInCalendarDirectory;
  8. @end
  9.  
  10. @implementation BMDirectorySetUp
  11. static NSString *nameOfFile;
  12. static NSString *imageURL;
  13. static NSString *calendarFolder;
  14.  
  15. - (void)checkCalendar {
  16.     if (!calendarFolder) {
  17.         [BMDirectorySetUp createDirForImage:@"CalendarFolder"];
  18.     }
  19.    
  20.     if (calendarFolder) {
  21.         [self numberOfImagesInCalendarDirectory];
  22.         [self downloadedImageOnDevice];
  23.         [self currentImageOnServer];
  24.         if ((_numberOfImagesInCalendarDirectory != 1) || (_downloadedImageOnDevice != _currentImageOnServer)) {
  25.            
  26.             //Get to the application directory
  27.             NSFileManager *fileManager = [NSFileManager defaultManager];
  28.             NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  29.             NSString *appDirectoryPath = paths[0];
  30.             NSString *directory = [appDirectoryPath stringByAppendingPathComponent:@"CalendarFolder/"];
  31.             //This is to delete files in the directory
  32.             NSError *error = nil;
  33.             for (NSString *file in [fileManager contentsOfDirectoryAtPath:directory error:&error]) {
  34.                 BOOL success = [fileManager removeItemAtPath:[NSString stringWithFormat:@"%@%@", directory, file] error:&error];
  35.                 if (!success || error) {
  36.                     // it failed.
  37.                     NSLog(@"Files didnt delete, error code %@", error);
  38.                 }
  39.             }
  40.             [BMDirectorySetUp downloadCalendarImage];
  41.         }
  42.        
  43.     }
  44. }
  45.  
  46. - (int)numberOfImagesInCalendarDirectory {
  47.     NSMutableString* bundlePath = [NSMutableString stringWithCapacity:4];
  48.     [bundlePath appendString:[[NSBundle mainBundle] bundlePath]];
  49.     [bundlePath appendString:calendarFolder];
  50.     NSArray *directoryContent  = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:bundlePath error:nil];
  51.     int numberOfFileInFolder = [directoryContent  count];
  52.     return numberOfFileInFolder;
  53. }
  54.  
  55. - (NSString*)downloadedImageOnDevice {
  56.     NSString *fileOnDevice;
  57.     NSString *imagePath;
  58.     NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  59.     NSString *appDirectoryPath = dirPaths[0];
  60.     NSString *calendarDir = [appDirectoryPath stringByAppendingPathComponent:@"/CalendarFolder/"];
  61.     NSArray *list = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:calendarDir error:nil];
  62.     for (NSString* file in list) {
  63.         if ([[file pathExtension] isEqualToString: @"png"]) {
  64.             imagePath = [calendarDir stringByAppendingPathComponent:file];
  65.         }
  66.         fileOnDevice = [imagePath lastPathComponent];
  67.         }
  68.     return fileOnDevice;
  69. }
  70.  
  71. - (NSString*)currentImageOnServer {
  72.     NSURL *JSONLocation = [NSURL URLWithString:@"http://radiolight.us/Calendar/dirList.php"];
  73.     NSString *pictureLocation = [NSString stringWithFormat:@"http://radiolight.us/Calendar/"];
  74.    
  75.     [[[NSURLSession sharedSession] dataTaskWithURL:JSONLocation
  76.                                  completionHandler:^(NSData *JSONdata, NSURLResponse *response, NSError *error) {
  77.                                      NSLog(@"%@ is the error code for currentImageOnServer", error);
  78.                                      // Process Data
  79.                                      NSError *jsonParsingError = nil;
  80.                                      NSArray *filesInDirectory = [NSJSONSerialization JSONObjectWithData:JSONdata
  81.                                                                                                  options:0
  82.                                                                                                    error:&jsonParsingError];
  83.                                      for (NSDictionary *dictionary in filesInDirectory) { NSString *fileName = dictionary[@"name"];
  84.                                          if ([[fileName pathExtension] isEqualToString: @"png"]) {
  85.                                              NSString *imagePath = [pictureLocation stringByAppendingPathComponent:fileName];
  86.                                              nameOfFile = fileName;
  87.                                              imageURL = imagePath;
  88.                                              NSLog(@"imageURL is %@", imageURL);
  89.                                          }
  90.                                          NSLog(@"Dictionary Deal finished, nameOfFile is now %@", nameOfFile);
  91.                                      }
  92.                                  }] resume];
  93.     return nameOfFile;
  94. }
  95.  
  96.  
  97. + (void)createDirForImage:(NSString *)CalendarDir {
  98.     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  99.     NSString *pathToCalendarDir = [[paths objectAtIndex:0] stringByAppendingPathComponent:CalendarDir];
  100.     calendarFolder = CalendarDir;
  101.     NSError *error;
  102.     //Does directory already exist?
  103.     if (![[NSFileManager defaultManager] fileExistsAtPath:pathToCalendarDir]) {
  104.         if (![[NSFileManager defaultManager] createDirectoryAtPath:pathToCalendarDir
  105.                                        withIntermediateDirectories:NO
  106.                                                         attributes:nil
  107.                                                              error:&error]) {
  108.             NSLog(@"Create directory error: %@", error);
  109.         }
  110.     }
  111. }
  112. /*
  113. + (void)fetchJSON {
  114.     NSURL *JSONLocation = [NSURL URLWithString:@"http://radiolight.us/Calendar/dirList.php"];
  115.     NSString *pictureLocation = [NSString stringWithFormat:@"http://radiolight.us/Calendar/"];
  116.    
  117.     [[[NSURLSession sharedSession] dataTaskWithURL:JSONLocation
  118.                                  completionHandler:^(NSData *JSONdata, NSURLResponse *response, NSError *error) {
  119.         // Process Data
  120.                                      NSError *jsonParsingError = nil;
  121.                                      NSArray *filesInDirectory = [NSJSONSerialization JSONObjectWithData:JSONdata
  122.                                                                                                options:0
  123.                                                                                                  error:&jsonParsingError];
  124.                                      
  125.                                      for (NSDictionary *dictionary in filesInDirectory) { NSString *fileName = dictionary[@"name"];
  126.                                          if ([[fileName pathExtension] isEqualToString: @"png"]) {
  127.                                              NSString *imagePath = [pictureLocation stringByAppendingPathComponent:fileName];
  128.                                              nameOfFile = fileName;
  129.                                              imageURL = imagePath;
  130.                                              NSLog(@"imageURL is %@", imageURL);
  131.                                          }
  132.                                          NSLog(@"Dictionary Deal finished, nameOfFile is now %@", nameOfFile);
  133.                                      }
  134.     }] resume];
  135. }
  136. */
  137. + (void)downloadCalendarImage {
  138.     // For this snippet we are downloading the same in two tasks.
  139.     NSString *imageUrl = @"http://www.radiolight.us/Calendar/ScreenPM.png";
  140.     // You always start by creating an NSURLConfiguration.
  141.     NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
  142.     // This creates a session using the current class as a delegate.
  143.     NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig
  144.                                                           delegate:self
  145.                                                      delegateQueue:nil];
  146.     //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.
  147.     NSURLSessionDownloadTask *getImageTask = [session downloadTaskWithURL:[NSURL URLWithString:imageURL]
  148.                                                         completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
  149.                                                             // Here you use the location variable provided in the completion handler to get a pointer to the image
  150.                                                             //UIImage *downloadedImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:location]];
  151.                                                             // Finally you could, for example, update UIImageView’s image to show the new file.
  152.                                                             dispatch_async(dispatch_get_main_queue(), ^{//scheduleImage.image = downloadedImage;
  153.                                                             });
  154.                                                            
  155.                                                             // This is me trying to add stuff... downloading the image to a file
  156.                                                             NSString *imageName = [imageUrl lastPathComponent];
  157.                                                            
  158.                                                             //  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  159.                                                            // NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
  160.                                                             NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  161.                                                             NSString *pathToCalendarDir = [[paths objectAtIndex:0] stringByAppendingString:@"/CalendarFolder/"];
  162.                                                            
  163.                                                            
  164.                                                             UIImage *imageToSave = [UIImage imageWithData:[NSData dataWithContentsOfURL:location]];
  165.                                                             NSData *binaryImageData = UIImagePNGRepresentation(imageToSave);
  166.                                                            
  167.                                                             BOOL writeSuccess = [binaryImageData writeToFile:[pathToCalendarDir stringByAppendingPathComponent:imageName] atomically:YES];
  168.                                                            
  169.                                                             if (writeSuccess)
  170.                                                                 NSLog(@"The image has been downloaded and saved.");
  171.                                                             else
  172.                                                                 NSLog(@"The saving of the Calendar image was unsuccessful.");
  173.                                                         }];
  174.     // You always have to start up the task!
  175.     [getImageTask resume];
  176. }
  177.  
  178.  
  179. // if you needed to track the download progress, for either task creation method, you would need to use the following:
  180. -(void)URLSession:(NSURLSession *)session
  181.      downloadTask:(NSURLSessionDownloadTask *)downloadTask
  182.      didWriteData:(int64_t)bytesWritten
  183. totalBytesWritten:(int64_t)totalBytesWritten
  184. totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
  185. {
  186.     NSLog(@"%f / %f", (double)totalBytesWritten,
  187.           (double)totalBytesExpectedToWrite);
  188. }
  189.  
  190.  
  191. @end
Advertisement
Add Comment
Please, Sign In to add comment