Swift: How to copy an entire view or a view controller

Swift:

var tempViewArchived = NSKeyedArchiver.archivedDataWithRootObject(sourceView)
var tempView = NSKeyedUnarchiver.unarchiveObjectWithData(tempViewArchived) as UIView

Objective-C:

NSData *tempArchiveView = [NSKeyedArchiver archivedDataWithRootObject:self.view];
UIView *viewOfSelf = [NSKeyedUnarchiver unarchiveObjectWithData:tempArchiveView];
//or
NSData *tempArchiveViewController = [NSKeyedArchiver archivedDataWithRootObject:self];
UIViewController *controller = [NSKeyedUnarchiver unarchiveObjectWithData:tempArchiveViewController];
Read More

Objective-C: Adding own method to Log in to Facebook view

Add FBLoginView as a property:

@property (nonatomic, strong) FBLoginView* loginView;

Add the code to make the view appear somewhere outside of the user’s real-estate:

    self.loginView = [[FBLoginView alloc] init];
    self.loginView.frame = CGRectMake(-500, -500, 0, 0);
    [self.view addSubview:self.loginView];
    self.loginView.delegate = self;

Then add, for example, an UIBarButton:

    UIBarButtonItem* fbButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(fireFbLoginView)];
    [self.navigationItem setRightBarButtonItem:fbButton];

The trick now is that when you click on the Bar button, it will simulate a click on the actual FBLoginView:

-(void)fireFbLoginView{
for(id object in self.loginView.subviews){
    if([[object class] isSubclassOfClass:[UIButton class]]){
        UIButton* button = (UIButton*)object;
        [button sendActionsForControlEvents:UIControlEventTouchUpInside];
    }
  }
}
Read More

Protected: Swift and Objective-C in the same project and Cocoapods

This content is password protected. To view it please enter your password below:

Read More

Objective-C: Add the network activity indicator to the status bar

    UIApplication* app = [UIApplication sharedApplication];
    app.networkActivityIndicatorVisible = YES;

And when you are finished downloading:

    UIApplication* app = [UIApplication sharedApplication];
    app.networkActivityIndicatorVisible = NO;
Read More

Objective-C: Add the pull to refresh mechanism

Add a new UIRefreshControl to your table.

    UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
    [refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
    [self.tableView addSubview:refreshControl];

Make sure that you stop the refresh once the method has been fired:

- (void)refresh:(UIRefreshControl *)refreshControl {
//do stuff
    [refreshControl endRefreshing];
}
Read More

Objective-C: How to intercept app state change (e.g. back to foreground)

In the app delegate, add the following, in the applicationDidBecomeActive, or in any of the methods that you want to track.

    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"UIApplicationDidReceiveRemoteNotification"
     object:self
     userInfo:nil];

– this will send a notification when the action happens.

In the ViewController.m, register the observer for this notification and create the appropriate selector.

    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(didReceiveRemoteNotification:)
     name:@"UIApplicationDidReceiveRemoteNotification1"
     object:nil];

-(void)didReceiveRemoteNotification:(NSDictionary *)userInfo {
    NSLog(@"%s", __FUNCTION__);
    if (self.isViewLoaded && self.view.window) {
        
    }
}

-(void)viewDidUnload {
    [[NSNotificationCenter defaultCenter]
     removeObserver:self
     name:@"UIApplicationDidReceiveRemoteNotification"
     object:nil];
}
Read More

Objective-C: Insert a batch of records in SQLite

NSString* statement;
    statement = @"BEGIN EXCLUSIVE TRANSACTION";
    sqlite3_stmt *beginStatement;
    if (sqlite3_prepare_v2(database, [statement UTF8String], -1, &beginStatement, NULL) != SQLITE_OK) {
        printf("db error: %s\n", sqlite3_errmsg(database)); 
        return;
    }
    if (sqlite3_step(beginStatement) != SQLITE_DONE) {
        sqlite3_finalize(beginStatement);
        printf("db error: %s\n", sqlite3_errmsg(database)); 
        return;
    }

    NSTimeInterval timestampB = [[NSDate date] timeIntervalSince1970];
    statement = @"INSERT OR REPLACE INTO item (hash, tag, owner, timestamp, dictionary) VALUES (?, ?, ?, ?, ?)";
    sqlite3_stmt *compiledStatement;
    if(sqlite3_prepare_v2(database, [statement UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK)
    {
        for(int i = 0; i < [items count]; i++){
            NSMutableDictionary* item = [items objectAtIndex:i];
            NSString* tag       = [item objectForKey:@"id"];
            NSInteger hash      = [[NSString stringWithFormat:@"%@%@", tag, ownerID] hash];
            NSInteger timestamp = [[item objectForKey:@"updated"] intValue];
            NSData *dictionary  = [NSKeyedArchiver archivedDataWithRootObject:item];

            sqlite3_bind_int(   compiledStatement, 1, hash);
            sqlite3_bind_text(  compiledStatement, 2, [tag UTF8String], -1, SQLITE_TRANSIENT);
            sqlite3_bind_text(  compiledStatement, 3, [ownerID UTF8String], -1, SQLITE_TRANSIENT);
            sqlite3_bind_int(   compiledStatement, 4, timestamp);
            sqlite3_bind_blob(  compiledStatement, 5, [dictionary bytes], [dictionary length], SQLITE_TRANSIENT);

            while(YES){
                NSInteger result = sqlite3_step(compiledStatement);
                if(result == SQLITE_DONE){
                    break;
                }
                else if(result != SQLITE_BUSY){
                    printf("db error: %s\n", sqlite3_errmsg(database)); 
                    break;
                }
            }
            sqlite3_reset(compiledStatement);
        }
        timestampB = [[NSDate date] timeIntervalSince1970] - timestampB;
        NSLog(@"Insert Time Taken: %f",timestampB);

        // COMMIT
        statement = @"COMMIT TRANSACTION";
        sqlite3_stmt *commitStatement;
        if (sqlite3_prepare_v2(database, [statement UTF8String], -1, &commitStatement, NULL) != SQLITE_OK) {
            printf("db error: %s\n", sqlite3_errmsg(database)); 
        }
        if (sqlite3_step(commitStatement) != SQLITE_DONE) {
            printf("db error: %s\n", sqlite3_errmsg(database)); 
        }

        sqlite3_finalize(beginStatement);
        sqlite3_finalize(compiledStatement);
        sqlite3_finalize(commitStatement);
Read More

Objective-C: PList manager for easy read/write plist files

PlistManager.h

//
//  PlistManager.h
//  Azi
//
//  Created by Cristian Ionescu on 26/02/14.
//  Copyright (c) 2014 Cristian Ionescu. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface PlistManager : NSObject

+(NSString *)getPathToPlistForResorce:(NSString *)resource;
+(NSMutableDictionary *)getDictionaryFromPath:(NSString *)pathToPlist;
+(BOOL)writeDictionary:(NSDictionary *)dictionary toPath:(NSString *)pathToPlist;
+(BOOL)updateSettingForKey:(NSString *)key withValue:(NSString *)value;
+(BOOL)doesFileExistAtPath:(NSString *)pathToPlist;
+(NSString *)getSettingValueForKey:(NSString *)key;

@end

PlistManager.m

//
//  PlistManager.m
//  Azi
//
//  Created by Cristian Ionescu on 26/02/14.
//  Copyright (c) 2014 Cristian Ionescu. All rights reserved.
//

#import "PlistManager.h"

@implementation PlistManager

+(NSString *)getPathToPlistForResorce:(NSString *)resource
{
    NSBundle *bundle = [NSBundle mainBundle];
    NSString *settingsPlistPath = [[[bundle bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"];

    return [settingsPlistPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist", resource]];
}

+(NSDictionary *)getDictionaryFromPath:(NSString *)pathToPlist
{
    return [NSDictionary dictionaryWithContentsOfFile:pathToPlist];
}

+(BOOL)writeDictionary:(NSDictionary *)dictionary toPath:(NSString *)pathToPlist
{
    return [dictionary writeToFile:pathToPlist atomically:YES];
}

+(BOOL)updateSettingForKey:(NSString *)key withValue:(NSString *)value
{
    NSString *settingsDictionaryPlistPath = [PlistManager getPathToPlistForResorce:@"Settings"];
    if ([PlistManager doesFileExistAtPath:settingsDictionaryPlistPath])
    {
        NSMutableDictionary *settingsDictionary = [PlistManager getDictionaryFromPath:settingsDictionaryPlistPath];
        [settingsDictionary setValue:value forKey:key];
        return [settingsDictionary writeToFile:settingsDictionaryPlistPath atomically:YES];
    }
    else
    {
        NSMutableDictionary *settingsDictionary = [NSMutableDictionary new];
        [settingsDictionary setValue:value forKey:key];
        return [settingsDictionary writeToFile:settingsDictionaryPlistPath atomically:YES];
    }
}

+(NSString *)getSettingValueForKey:(NSString *)key
{
    NSDictionary *settingsDictionary = [PlistManager getDictionaryFromPath:[PlistManager getPathToPlistForResorce:@"Settings"]];
    return [settingsDictionary valueForKey:key];
}

+(BOOL)doesFileExistAtPath:(NSString *)pathToPlist
{
    NSFileManager *fileManager = [NSFileManager new];
    return [fileManager fileExistsAtPath:pathToPlist];
}


@end
Read More

Objective-C: Checking for a network connection

First read here: http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html

Now, you don’t have to ho through all the codes in sample app, just follow these few steps to check internet connection in our app :

  • Add the SystemConfiguration.framework to your project.
  • Add the files Reachability.h and Reachability.m only from the Reachability sample code you just downloaded to your project.
  • Add the following code in the implementation file where you need to test the Internet connection.
#import "Reachability.h"

        //// Just use it ,Where you need it  (checking internet connection)
        Reachability *reachTest = [Reachability reachabilityWithHostName:@"www.apple.com"];     
        NetworkStatus internetStatus = [reachTest  currentReachabilityStatus];    
        
         if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)){   
                  /// Create an alert if connection doesn't work,no internet connection   
               UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"No Internet Connection" 
                                                         message:@"You require an internet connection via WiFi or cellular   
                                                         network for location finding to work."  delegate:self  
                                                         cancelButtonTitle:@"Ok"  otherButtonTitles:nil];  
                 [myAlert show];  
               } 
      else{  
               // There is a internet connection
              /// Do,Whatever you want  
        }  
Read More

Objective-C: Add background to UILabel

NSMutableAttributedString *s =
     [[NSMutableAttributedString alloc] initWithString:yourString];

[s addAttribute:NSBackgroundColorAttributeName
          value:[UIColor greenColor]
          range:NSMakeRange(0, s.length)];

label.attributedText = s;
Read More