Life & Technology

Handful lessons in different areas of technology and life in general.

Category Archives: Uncategorized

GCNetworkKit: Download with progress via UIAlertView

For the past few months, I’ve been using this simple to use yet powerful HTTP set of classes called GCNetworkKit to communicate to your server with ease. For a brief description from the github page:

GCNetworkKit is a helpful set of classes for interacting with a http server. All classes make use of ARC. In order to use it you need to drag the folder into your xcode project. You also need to add the MobileCoreServices and the SystemConfiguration framework to your project.

And with this, I’ve come up with a simple example that demonstrate the ease of use of this library.

UIAlertView + UIProgressView

For this demo, we want to have a file download functionality that we need to display via UIAlertView with additional UIProgressView to view the progress and a UILabel to determine the total percentage completion. These two subviews will be attached to our UIAlertView and will be used during the file downloading. If you downloaded the app called CityMaps2Go, the way they present their maps download is exactly what we’ll be creating.

Our initial screen will look like this:

Next, we will hook our UIButton to trigger the display of UIAlertView on the screen and immediately start the process.

  1. -(IBAction)download:(id)sender
  2. {
  3.     NSURL *fileURL = [NSURL URLWithString:@”http://YOUR_URL_HERE/PATH/TO/FILE.pdf”%5D;
  4.     downloadAlertView = [[UIAlertView alloc] initWithTitle:@”Downloading…”
  5.                                                     message:@”             “
  6.                                                    delegate:self
  7.                                           cancelButtonTitle:@”Cancel”
  8.                                           otherButtonTitles:nil];
  9.     [progressView setProgress:0];
  10.     [downloadAlertView addSubview:progressView];
  11.     [downloadAlertView addSubview:progressLabel];
  12.     [progressView setProgressViewStyle: UIProgressViewStyleBar];
  13.     [downloadAlertView show];
  14.     [self downloadDataAtURL:fileURL];
  15. }

After adding the UIProgressView and UILabel on our UIAlertView, we will call our method that will actually perform the file downloading. Line 16 will start to call GCNetworkKit’s block-based methods as follows:

  1. – (void)downloadDataAtURL:(NSURL *)url {
  2.     __GC_weak ViewController *weakReference = self;
  3.     weakReference.progressLabel.text = @”Preparing …”;
  4.     [self performSelectorOnMainThread:@selector(updateStatusLabel:) withObject:@”> Status: Download Starting” waitUntilDone:NO];
  5.     GCNetworkDownloadRequest *request = [GCNetworkDownloadRequest requestWithURL:url];
  6.     request.autoDeleteTMPFile = YES;
  7.     request.loadWhileScrolling = YES;
  8.     request.continueInBackground = YES;
  9.     request.progressHandler = ^(CGFloat progress){
  10.         NSLog(@”Progress on downloading data: %f.”, progress);
  11.         [weakReference updateProgress:progress];
  12.     };
  13.     request.downloadCompletionHandler = ^(NSString *filePath){
  14.         self.requestHash = nil;
  15.         [self performSelectorOnMainThread:@selector(updateStatusLabel:) withObject:@”> Status: Download Completed.” waitUntilDone:NO];
  16.         [downloadAlertView dismissWithClickedButtonIndex:0 animated:YES];
  17.         NSLog(@”Downlaoded data and saved at: %@.”, filePath);
  18.         UIAlertView *success = [[UIAlertView alloc] initWithTitle:@”Download Status” message:@”File successfully downloaded!” delegate:nil cancelButtonTitle:@”Great!” otherButtonTitles: nil];
  19.         [success show];
  20.     };
  21.     self.requestHash = [[GCNetworkRequestQueue sharedQueue] addRequest:request];
  22. }

You see on Line 11, we don’t have to worry getting the current progress status of the file being downloaded, GCNetworkKit already has this functionality built-in. And on Line 15 is the completionHandler callback that we can use to process the file being downloaded or even display another UIAlertView that will popup the completion alert message.

And if we like to cancel the download process, we only need to call cancelRequestWithHash: method to immediately halt the current operation. This is possible because every request that is put in the queue automatically has a unique id in the form of hash.

  1. – (void) cancelDownload
  2. {
  3.     [[GCNetworkRequestQueue sharedQueue] cancelRequestWithHash:self.requestHash];
  4.     self.requestHash = nil;
  5. }

Using GCNetworkKit library, we achieved our task with minimal effort in coding and the result is exactly what we expected!

Screenshots for our demo project

The XCode project is compiled under ARC and available for download here.

Advertisements

NSString Category Function: isIn()

Usually when we’re trying to check if two strings are equal, we often used this code:

 NSString *isoView = @"Isometric View";
 if([isoView isEqualToString:@"Parallel View"]) // do something

Which is fine but if you’re testing against multiple values for equality, you might end up writing code like this:

 NSString *isoView = @"Isometric View";
 if([isoView isEqualToString:@"Parallel View"] || [isoView isEqualToString:@"Dynamic View"]
    || [isoView isEqualToString:@"Inverted View"] || [isoView isEqualToString:@"Range View"])
     // Do somethng here

And you’re code will contain bunch of ORs ( || ) just to test if your string matches to your qualifiers.

NSString+Additions
With this problem, I have created a simple NSString Category that basically solves this kind of situation and improves your code a little bit. I created a boolean function that accepts multiple string values terminated by nil that will be used for equality check of string.

Our interface header looks like this:

// NSString+Additions.h
#import <Foundation/Foundation.h>

@interface NSString (Additions)
- (BOOL) isIn: (NSString *) strings, ... NS_REQUIRES_NIL_TERMINATION;
@end

And the implementation code is a simple for .. loop to achieve our goal:

// NSString+Additions.m
#import "NSString+Additions.h"

@implementation NSString (Additions)

- (BOOL) isIn: (NSString *) strings, ...
{
    BOOL isFound = NO;

    va_list args;
    va_start(args, strings);
    for (NSString *arg = strings; arg != nil; arg = va_arg(args, NSString*))
    {
        if ([self caseInsensitiveCompare:arg] == NSOrderedSame) {
            isFound = YES;
            break;
        }
    }
    va_end(args);

    return isFound;
}
@end

If we’re going back to our sample snippets above, we would then write the conditional checking as follows:

NSString *isoView = @"Isometric View";
if ([isoView isIn:@"Parallel View", @"Dynamic View", @"Inverted View", @"Range View", nil])
   // Do Something

Simple and not cluttering with OR ( || ) statements!

The basic principle on the above Category is based on Objective C feature called Variable Argument Lists which is explained clearly by Matt on his blog post.

The category is easy to override to include checking against NSArray or NSDictionary.

Mac OS X Lion: Hide Guest User Account

Recently, I upgraded my MacBook Pro to the latest incremental update of Lion which is version 10.7.2. The upgrade went fine but I noticed that upon logging-in, the Guest user account is now visible/appearing from my login screen every time I boot up my Mac. I thought this was caused by iCloud and Find My Mac feature of OSX Lion but it’s not!

Hiding back the Guest user can be achieved by Checking a single checkbox found under Security & Privacy of your Mac’s System Preferences. Restart. Voila! Guest User account is now gone on my login screen window!

The Fix:
1. Go to System Preferences
2. Under Personal section, click the Security & Privacy icon
3. Click the ‘lock’ icon to make changes.
4. Under General tab, just check the option box titled “Disabling restarting to Safari when screen is locked
5. Click the lock key again to secure your preferences.
6. Restart your machine
7. No Guest User will be displayed on the Login Screen Window

Screenshot:

Security & Privacy Window

MyBusyBee TextBlast Security Flawed

This week, I did install this software from their website as they provide a downloadable package with varying types (Basic to Enterprise) and with varying prices. So, I installed the Enterprise version of the product and see how the software works.

And upon launching, I determined that they’re using an “offline” activation which means all the activation logic resides on the program. And here’s what I discovered:

  • Serial number field is based on machine’s hard disk which is why the activation key will only work on the specified/given serial number.
  • Activation key is just based on partial data of the serial number, the license type (Date duration or Unlimited) and the date of activation.
  • After decryption of the activation key, it just simply validates if the given string is equal to “UnLimited” or a given string date. If the given string is “UnLimited”, end of story, no further validation will be checked and your copy of this software is yours perpetually without having to renew your activatin key each month which is exactly what you’re paying for based on your package type (Enterprise cost is Php 5000.00).
  • Embedding password for your MS Access database is not security at all.
  • Encryption and decryption both happening within the program and this is not a good practice of security unless the process of decrypting is not a simple one (sort of having a looping algorithm that will actually translates to the actual string).

And with these discoveries, it just a matter of minutes and my downloaded version of the product is now licensed for a lifetime.

busybee_fullversion

I hope developer/s of this software should carefully examine how best to protect their software so that their customers will always feel that the money they are paying for is worth to the product they are using.