Showing posts with label objective C. Show all posts
Showing posts with label objective C. Show all posts

Objective C: UITableView: Detect which section header on top

static NSInteger currentTopVisibleSection = -1;

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSIndexPath *topCellPath = [[tableView indexPathsForVisibleRows] objectAtIndex:0];
    if (currentTopVisibleSection != topCellPath.section) {
        currentTopVisibleSection = topCellPath.section;
        NSLog(@"current section on top is %d", currentTopVisibleSection);
    }

    NSString *header = [NSString stringWithFormat:@"Section %d", section];
    return header;
}

Objective C: UITextField controlling background image/color

If you set
UITextField *tf = [[UITextField alloc] init];
tf.borderStyle = UITextBorderStyleRoundedRect;
you can't control background of text field. To controlling background you need
#import "QuartzCore/QuartzCore.h"
...

UITextField *tf = [[UITextField alloc] init];
tf.borderStyle = UITextBorderStyleDefault;
tf.background = [UIImage imageNamed:@"bg_000000_20.png"];
tf.layer.cornerRadius = 5.0;
tf.layer.masksToBounds = YES;

// for vertical align
tf.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;

// for border
tf.layer.borderWidth = 1.0;
tf.layer.borderColor = [[UIColor darkGrayColor] CGColor];

// for left padding
tf.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)];
tf.leftViewMode = UITextFieldViewModeAlways;

Objective C: Detect start of bouncing effect for UIScrollView

For detect bouncing of UIScrollView (or UITableView ...) using UIScrollViewDelegate:
static BOOL _draggingView = NO;

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
 _draggingView = YES;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
 _draggingView = NO;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
 NSInteger pullingDetectFrom = 50;
 if (self.contentOffset.y < -pullingDetectFrom) {
  _draggingView = NO;
  NSLog(@"Pull Down");
 } else if (self.contentSize.height <= self.frame.size.height && self.contentOffset.y > pullingDetectFrom) {
  _draggingView = NO;
  NSLog(@"Pull Up");
 } else if (self.contentSize.height > self.frame.size.height && 
       self.contentSize.height-self.frame.size.height-self.contentOffset.y < -pullingDetectFrom) {
  _draggingView = NO;
  NSLog(@"Pull Up");
 }
}

Objective C: Sort array of objects

If we have array of some objects:
@interface SimpleObject : NSObject {
 NSInteger key;
 NSString *name;
        . . .
}
and we need to sort this array by "name" property of SimpleObject. Use NSSortDescriptor:
// declare array with SimpleObject instances
self.simpleObjectsArray = . . .

NSSortDescriptor *sortDescriptor =
        [[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES] autorelease];
NSArray *sortDescriptors = 
        [NSArray arrayWithObject:sortDescriptor];
// array contained all instances sorted by "name" field
NSArray *sortedArray = 
        [self.simpleObjectsArray sortedArrayUsingDescriptors:sortDescriptors];

Objective C: Bring back user to your application during/after he End the Call

Sometime you need come back to application after phone call initiated by your own application.
Exist two options (each from them not 100% that do you want), but if no choice..

  1. After starting phone call you getting local notification alert with two option
    • Cancel (stay on call screen)
    • Return (back to application during your call)
    NSURL *phoneSchemaURL = [NSURL URLWithString:@"tel://123456789"];
     
    [[UIApplication sharedApplication] openURL:phoneSchemaURL];
    
    UILocalNotification *localNotification = [[UILocalNotification alloc] init];
    if (localNotification != nil) {
     NSDate *notificationDate = [[NSDate alloc] initWithTimeIntervalSinceNow: 3];
      
     localNotification.fireDate = notificationDate;
     [notificationDate release];
      
     localNotification.alertBody = @"Stay in app";
     localNotification.alertAction = @"Return";
      
     localNotification.soundName = UILocalNotificationDefaultSoundName;
      
     [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
    }
    [localNotification release];
    
  2. After ending phone call your application retrieve focus.
    NSURL *phoneSchemaURL = [NSURL URLWithString:@"tel://123456789"];
     
     NSString *osVersion = [[UIDevice currentDevice] systemVersion];
     
    if([osVersion compare: @"3.1" options: NSNumericSearch] >= NSOrderedSame ) {
     UIWebView *webview = [[UIWebView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];
     //or if you just want to call and back to application
     //UIWebView *webview = [[UIWebView alloc] init];
    
     [webview loadRequest:[NSURLRequest requestWithURL:phoneSchemaURL]];
      
     //if you just want to call and back to application remark code below, but don't forget release webview
     [self.view addSubview:webview];
     [webview release];
    } else {
     // On 3.0 and below, dial as usual
     [[UIApplication sharedApplication] openURL: phoneSchemaURL];          
    }
    

Objective C: Basic HTTP Authorization


  1.  First version of "Authorization":
    NSString *loginString = [NSString stringWithFormat:@"%@:%@", [self userName], [self password]];
    NSString *encodedLoginData = [Base64 encode:[loginString dataUsingEncoding:NSUTF8StringEncoding]];  
    NSString *base64LoginData = [NSString stringWithFormat:@"Basic %@",encodedLoginData];
    
    NSURL *url=[NSURL URLWithString:@"http://my_url.com"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                    timeoutInterval:10.0];
    
    [request setHTTPMethod:@"POST"];
    
    [request setValue:base64LoginData forHTTPHeaderField:@"Authorization"];
    
    NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
  2. Second version of "Authorization":
    NSURL *URL = [NSURL URLWithString:url];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy
                                         timeoutInterval:10.0];
    
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    NSURLConnection Delegates
    - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
        if ([challenge previousFailureCount] == 0) {
            NSLog(@"received authentication challenge");
            NSURLCredential *newCredential = [NSURLCredential credentialWithUser:@"USER"
                                                                        password:@"PASSWORD"
                                                                     persistence:NSURLCredentialPersistenceForSession];
            NSLog(@"credential created");
            [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
            NSLog(@"responded to authentication challenge");    
        }
        else {
            NSLog(@"previous authentication failure");
        }
    }
    

Objective C: Change title of back button in navigation bar

You need change title of the back button from view controller which call to next view controller:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.detailsViewController == nil) {
        self.detailsViewController = [[DetailsViewController alloc] initWithNibName:@"DetailsViewController" bundle:nil];
 }
 
 [self.navigationController pushViewController:detailsViewController animated:YES];
 
 [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)viewDidLoad {
 self.title = NSLocalizedString(@"root_tab_title_0", @"My Title");

 //Set title for back button to this controller
 self.navigationItem.backBarButtonItem =
  [[[UIBarButtonItem alloc] initWithTitle:@"My back button"
      style:UIBarButtonItemStyleBordered
      target:nil
      action:nil] autorelease];
}

Objective C: Change title font in navigation bar

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
label.textAlignment = UITextAlignmentCenter;
label.adjustsFontSizeToFitWidth = YES;
label.minimumFontSize = 10.0;
[label setFont:[UIFont boldSystemFontOfSize:16.0]];
[label setBackgroundColor:[UIColor clearColor]];
[label setTextColor:[UIColor whiteColor]];
[label setText:@"My Favorite Title"];

[self.navigationItem setTitleView:label];
[label release];

Xcode: include ObjectiveC categories int static library

If you need to include ObjectiveC categories or other framework using ObjectiveC categories ( for example JSON framework ) into your own static library you probably get


-[__NSCFDictionary JSONRepresentation]: unrecognized selector sent to instance


In your project that using your static library you need to set in Project Settings for "Other Linker Flags" property two additional flags:

-ObjC
-all_load


Objective C: Merge two images

+ (UIImage*)mergeImage:(UIImage*)first withImage:(UIImage*)second
{
 // get size of the first image
 CGImageRef firstImageRef = first.CGImage;
 CGFloat firstWidth = CGImageGetWidth(firstImageRef);
 CGFloat firstHeight = CGImageGetHeight(firstImageRef);
 
 // get size of the second image
 CGImageRef secondImageRef = second.CGImage;
 CGFloat secondWidth = CGImageGetWidth(secondImageRef);
 CGFloat secondHeight = CGImageGetHeight(secondImageRef);
 
 // build merged size
 CGSize mergedSize = CGSizeMake(MAX(firstWidth, secondWidth), MAX(firstHeight, secondHeight));
 
 // capture image context ref
 UIGraphicsBeginImageContext(mergedSize);
 
 //Draw images onto the context
 [first drawInRect:CGRectMake(0, 0, firstWidth, firstHeight)];
 [second drawInRect:CGRectMake(0, 0, secondWidth, secondHeight)]; 
 
 // assign context to new UIImage
 UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
 
 // end context
 UIGraphicsEndImageContext();

 return newImage;
}

If you want to resize new image to new desired size use function from previous post.

Objective C: Resize image

+ (UIImage*)resizeImageWithImage:(UIImage*)image toSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
 
    // draw in new context, with the new size
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
 
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
 
    // End the context
    UIGraphicsEndImageContext();
 
    return newImage;
}

Zip/Unzip files on iPhone/iPad/iOS


  1. Download ZipArchive from http://code.google.com/p/ziparchive/downloads/list.
  2. Drag into project.
  3. Add to project existing framework libz.1.2.3.dylib (last version).
  4. Import to project:
    #import "ZipArchive.h"
    
  5. Uncompress zip file example:
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSString *zipFilePath = [documentsDirectory stringByAppendingPathComponent:@"myZipFileName.zip"];
    
    NSString *output = [documentsDirectory stringByAppendingPathComponent:@"unZipDirName"];
    
    ZipArchive* za = [[ZipArchive alloc] init];
    
    if( [za UnzipOpenFile:zipFilePath] ) {
        if( [za UnzipFileTo:output overWrite:YES] != NO ) {
            //unzip data success
            //do something
        }
    
        [za UnzipCloseFile];
    }
    
    [za release];
    
  6. Compress directory or file example:
    BOOL isDir=NO;
    
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSArray *subpaths;
    
    NSString *toCompress = [NSString stringWithString:@"dirToZip_OR_fileNameToZip"];
    NSString *pathToCompress = [documentsDirectory stringByAppendingPathComponent:toCompress];
    
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    if ([fileManager fileExistsAtPath:pathToCompress isDirectory:&isDir] && isDir){
        subpaths = [fileManager subpathsAtPath:pathToCompress];
    } else if ([fileManager fileExistsAtPath:pathToCompress]) {
        subpaths = [NSArray arrayWithObject:pathToCompress];
    }
    
    NSString *zipFilePath = [documentsDirectory stringByAppendingPathComponent:@"myZipFileName.zip"];
      
    ZipArchive *za = [[ZipArchive alloc] init];
    [za CreateZipFile2:zipFilePath];
    if (isDir) {
        for(NSString *path in subpaths){  
            NSString *fullPath = [pathToCompress stringByAppendingPathComponent:path];
            if([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && !isDir){
                [za addFileToZip:fullPath newname:path];  
            }
        }
    } else {
        [za addFileToZip:pathToCompress newname:toCompress];
    }
    
    BOOL successCompressing = [archiver CloseZipFile2];