Powered By Blogger
Showing posts with label iOS SDK. Show all posts
Showing posts with label iOS SDK. Show all posts

Friday, May 3, 2019

how to record/capture screen in iOS with the help of Swift programming?

Hello everyone,

- Nowadays, I'm working for screen recording operation in my one of the projects and it's really an interesting one which I want to share with my blog's followers.

- Please check below code lines for detailed information about implementation with Swift.


import Foundation
import ReplayKit
import AVKit

/// A customised class for Video & Audio recording functionality
class ScreenRecorder {
    var assetWriter: AVAssetWriter?
    var videoInput: AVAssetWriterInput?
    var audioInput: AVAssetWriterInput?
    var recorder = RPScreenRecorder.shared()
    var fileURL: URL?
    var timer: Timer?
    
    // MARK: ====================================
    // MARK: ScreenRecorder with Capture Screen event
    // MARK: ====================================
    
    func startRecording(withFilepath fileURL: URL, recordingHandler:@escaping (Error?) -> Void) {
        do {
            assetWriter = try AVAssetWriter(outputURL: fileURL, fileType:
                AVFileType.mp4)
            //-- Video Input
            let videoOutputSettings: [String: Any] = [
                AVVideoCodecKey: AVVideoCodecType.h264,
                AVVideoWidthKey: UIScreen.main.bounds.size.width,
                AVVideoHeightKey: UIScreen.main.bounds.size.height,
                AVVideoCompressionPropertiesKey: [AVVideoAverageBitRateKey: 2300000,
                                                  AVVideoProfileLevelKey: AVVideoProfileLevelH264High40]
            ]
            //-- Audio Input
            var channelLayout = AudioChannelLayout()
            channelLayout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_5_1_D
            let audioOutputSettings: [String: Any] = [
                AVNumberOfChannelsKey: 6,
                AVFormatIDKey: kAudioFormatMPEG4AAC_HE,
                AVSampleRateKey: 44100,
                AVEncoderBitRateKey: 128000,
                AVChannelLayoutKey: NSData(bytes: &channelLayout, length: MemoryLayout.size(ofValue: channelLayout))
            ]
            
            audioInput = AVAssetWriterInput(mediaType: .audio, outputSettings: audioOutputSettings)
            videoInput = AVAssetWriterInput (mediaType: .video, outputSettings: videoOutputSettings)
            
            audioInput?.expectsMediaDataInRealTime = true
            videoInput?.expectsMediaDataInRealTime = true
            
            assetWriter?.add(audioInput!)
            assetWriter?.add(videoInput!)
            
            recorder.isMicrophoneEnabled = true
            recorder.startCapture(handler: { (sample, bufferType, error) in
                recordingHandler(error)
                if CMSampleBufferDataIsReady(sample) {
                    if self.assetWriter?.status == AVAssetWriter.Status.unknown {
                        self.assetWriter?.startWriting()
                        self.assetWriter?.startSession(atSourceTime: CMSampleBufferGetPresentationTimeStamp(sample))
                    }
                    if self.assetWriter?.status == AVAssetWriter.Status.failed {
                        print("Error occured, status = \(String(describing: self.assetWriter?.status.rawValue)), \(String(describing: self.assetWriter?.error?.localizedDescription)) \(String(describing: self.assetWriter?.error))")
                        self.assetWriter?.cancelWriting()
                        self.assetWriter?.endSession(atSourceTime: CMSampleBufferGetPresentationTimeStamp(sample))
                        recordingHandler(error)
                        return
                    }
                    //-- Video Data
                    if (bufferType == .video), let isReadyForMoreMediaData = self.videoInput?.isReadyForMoreMediaData, isReadyForMoreMediaData == true {
                        self.videoInput?.append(sample)
                    }
                    //-- Audio Data
                    if (bufferType == .audioApp || bufferType == .audioMic), let isReadyForMoreMediaData = self.audioInput?.isReadyForMoreMediaData, isReadyForMoreMediaData == true {
                        self.audioInput?.append(sample)
                    }
                }
            }, completionHandler: { (error) in
                recordingHandler(error)
            })
        } catch {
            recordingHandler(error)
        }
    }
    
    func stopRecording(handler: @escaping (Error?) -> Void) {
        recorder.stopCapture { (error) in
            handler(error)
            if self.assetWriter?.status == AVAssetWriter.Status.failed || self.assetWriter?.status == AVAssetWriter.Status.cancelled || self.assetWriter?.status == AVAssetWriter.Status.unknown || self.assetWriter?.status == AVAssetWriter.Status.completed {
                return
            } else {
                self.audioInput?.markAsFinished()
                self.videoInput?.markAsFinished()
                self.assetWriter?.finishWriting(completionHandler: {
                })
            }
        }
    }
    
   class func createReplaysFolder() {
        // path to documents directory
        let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
        if let documentDirectoryPath = documentDirectoryPath {
            // create the custom folder path
            let replayDirectoryPath = documentDirectoryPath.appending("/Replays")
            let fileManager = FileManager.default
            if !fileManager.fileExists(atPath: replayDirectoryPath) {
                do {
                    try fileManager.createDirectory(atPath: replayDirectoryPath,
                                                    withIntermediateDirectories: false,
                                                    attributes: nil)
                } catch {
                    print("Error creating Replays folder in documents dir: \(error)")
                }
            }
        }
    }
    
   class func filePath(_ fileName: String) -> String {
        createReplaysFolder()
        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        let documentsDirectory = paths[0] as String
        let filePath: String = "\(documentsDirectory)/Replays/\(fileName).mp4"
        return filePath
    }
}

// MARK: ====================================
// MARK: ScreenRecorder with Recording Event
// MARK: ====================================

extension ScreenRecorder {
    //-- Start screen recording event
    func startRecording(recordingHandler: @escaping(String?) -> Void) {
        guard recorder.isAvailable else {
            recordingHandler("Recording is not available at this time.")
            return
        }
        //recorder.delegate = self
        recorder.isMicrophoneEnabled = true
        recorder.startRecording{ (error) in
            if error == nil {
                #if DEBUG
                print("Started Recording Successfully")
                #endif
                recordingHandler(nil)
            } else {
                recordingHandler(error?.localizedDescription)
            }
        }
    }
    
    //-- Stop screen recording event
    func stopRecording(recordingHandler: @escaping(RPPreviewViewController?, Error?) -> Void) {
        recorder.stopRecording { (preview, error) in
            recordingHandler(preview, error)
        }
    }
}

- Please create one ScreenRecorder.swift file and add the above contents to that file. After this, please import this to another class where you want to implement this functionality. 



For example :


/// Video button click event

@IBAction func btnVideoClicked(_ sender: UIButton) {
    
    sender.isSelected = !sender.isSelected
    
    if sender.isSelected {
        
        startScreenRecording()
        
    } else {
        
        stopScreenRecording()
        
    }
    
}

// MARK: ====================================
// MARK: Start Capturing Part
// MARK: ====================================

/// Start event for Screen Recording
func startScreenRecording() {
    let fileURL = URL(fileURLWithPath: filePath("Recording_\(Date().convertToStringWith(Constants.DateFormates.filedateformat)!)"))
    screenRecorder. startRecording(withFilepath: fileURL!) { (error) in
        if error == nil {
            
        } else {
            #if DEBUG
            print(error ?? "")
            #endif
            sender.isSelected = !sender.isSelected
        }
    }
}

// MARK: ====================================
// MARK: Stop Capturing Part
// MARK: ====================================

/// stop event for Screen Recording
func stopScreenRecording() {
    screenRecorder.stopRecording{ (error) in
        if error == nil {
            sender.isSelected = !sender.isSelected
            // An alert will be displayed to save or delete recorded video
            displayAlertToSaveOrDeleteVideo()
        } else {
            #if DEBUG
            print(error ?? "")
            #endif
        }
    }
}

/// A function to display an alert to save or delete the recorded video
func displayAlertToSaveOrDeleteVideo() {
    DispatchQueue.main.async(execute: {
        let alert = UIAlertController(title: "Recording Finished", message: "Do you want to save or delete recording?", preferredStyle: .alert)
        let deleteAction = UIAlertAction(title: "Delete", style: .destructive, handler: { (action: UIAlertAction) in
            DispatchQueue.main.async(execute: {
                //-- Share annoted image's local path to upload it on server.
                if let savedAnnotedFilePath = screenRecorder.assetWriter?.outputURL.path, FileManager.shared.fileExists(atPath: savedAnnotedFilePath) {
                    do {
                        try AppInfo.shared.fileManager.removeItem(atPath: savedAnnotedFilePath)

                    // recording deleted successfully

                        
                    } catch {
                        self.view?.makeToast(error.localizedDescription)
                    }
                } else {
                    // recorded_file_not_found
                }
            })
        })
        let editAction = UIAlertAction(title: "Save", style: .default, handler: { (action: UIAlertAction) -> Void in
            DispatchQueue.main.async(execute: {
                //-- Share annoted image's local path to upload it on server.
                if let savedAnnotedFilePath = self.assetWriter?.outputURL.path, AppInfo.shared.fileManager.fileExists(atPath: savedAnnotedFilePath) {
                    // MOVE OR UPLOAD FILE TO DESNTINATION
                } else {
                    // recorded_file_not_found
                }
            })
        })
        alert.addAction(editAction)
        alert.addAction(deleteAction)
        self.present(alert, animated: true, completion: nil)
    })
}


- Try this in your project, you will definitely get success and in case of any issue, post your comment. I will try to respond to it with an appropriate solution.


Regards,

Monday, January 27, 2014

Asynchronous image downloading with dispatch_async queue

Hi,

There's no need to implement any framework for LazyImage loading as of now. You can do it simply by writing few lines of code below.. Just take a look..


Example : 

UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc]init];
UIImageView * userImage = [[UIImageView alloc]init];

        [activity startAnimating];
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
        dispatch_async(queue, ^(void) {
            //  You may want to cache this explicitly instead of reloading every time.
            NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
            UIImage* image = [[UIImage alloc] initWithData:imageData];
            dispatch_async(dispatch_get_main_queue(), ^{
                // Capture the indexPath variable, not the cell variable, and use that
               userImage.image = image;
                [activity stopAnimating];
            });
       });


Regards,
Nilesh M. Prajapati

Tuesday, October 22, 2013

How can we extract numbers from a string in iPhone?

Hi,

Here is the way to separate numbers from a mixed character string. For this , anybody can use "NSScanner" in their own way. I use this one to filter numbers from the given input string. Please have look ...

For Example : 

NSString *string = @"45#%ds32(())_*x 34";
NSMutableString *newStrStrip = [NSMutableString
        stringWithCapacity:newStrStrip.length];

NSScanner *scanner = [NSScanner scannerWithString:string];
NSCharacterSet *numbers = [NSCharacterSet
        characterSetWithCharactersInString:@"0123456789"];

while ([scanner isAtEnd] == NO)
{
  NSString *buffer;
      if ([scanner scanCharactersFromSet:numbers intoString:&buffer])
     {
          [newStrStrip appendString:buffer];
     }
     else
     {
          [scanner setScanLocation:([scanner scanLocation] + 1)];
     }
}

NSLog(@"OUTPUT : %@", newStrStrip);  // "OUTPUT : 453234"


Regards,
Nilesh M. Prajapati

Monday, July 1, 2013

Custom refresh control in iPhone

Hi,
Everyone,

Did you ever use "Custom Refresh Control" in your iOS application? I recently implemented this concept in my one of code. There's a ready-made control available called "ODRefreshControl"

You just need to import to files into your project resource. "ODRefreshControl.h" & "ODRefreshControl.m". Please check below lines to use it in your code.

*******For Example :

1) Import Files : "ODRefreshControl.h" & "ODRefreshControl.m"
2) Put this into your class file.

- (void)viewDidLoad
{

    ODRefreshControl *refreshControl = [[ODRefreshControl alloc] initInScrollView:tbl_tableView]; // Assign your view in which you want to use it. I used it in my UITableViewController.
    [refreshControl addTarget:self action:@selector(dropViewDidBeginRefreshing:)  forControlEvents:UIControlEventValueChanged];

 [super viewDidLoad];
}

#pragma mark ---------------
#pragma mark UITableView Pull-To-Refresh Management
#pragma mark ---------------

- (void)dropViewDidBeginRefreshing:(ODRefreshControl *)refreshControl
{
    double delayInSeconds = 1.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [refreshControl endRefreshing];
          // write your own refresh method here which you want to call.
    });
}

Thanks,
Nilesh M. Prajapati

Thursday, May 23, 2013

What should be the alternative of horizontal scrolling table in iOS?

Hi,
Dear readers,

Now a days, I came across a new requirement of horizontal scrolling table view. I made some research for it and I found a new library as a unique solution for this. The library is known as "iCarousel" library. You just need to add that 2 files into your project source and after then you can import ".h"(header) file in your class where-ever you want to make such view effect.

Download Link : https://github.com/nicklockwood/iCarousel



After downloading two source files "iCarousel.h" & "iCarousel.m". Follow the below steps to integrate it in your project.

*** Step 1: Create a view of iCarousel in header file and bind it with .XIB file.
    - For ex. : IBOutlet iCarousel *carousel;

*** Step 2: Then place its data-source and delegate methods in implementation section of a view controller.

*** Step 3: Set the delegate of a iCarousel.

*** Step 4: Set the type of a iCarousel in ViewDidLoad method.

- (void)viewDidLoad
{
       [super viewDidLoad];

        carousel.type = iCarouselTypeLinear;
        carousel.vertical = NO;
        carousel.scrollOffset = 1.0;
        carousel.centerItemWhenSelected = NO;
        carousel.stopAtItemBoundary = YES;
        carousel.scrollToItemBoundary = NO;
}

***Step 5: And finally put the below code into implementation section of a view controller.

#pragma mark -------------------
#pragma mark iCarousel Delegate methods
#pragma mark -------------------


- (NSUInteger)numberOfItemsInCarousel:(iCarousel *)carousel
{
    //generate 100 buttons
    //normally we'd use a backing array
    //as shown in the basic iOS example
    //but for this example we haven't bothered
    return [businessArr count];
}

- (UIView *)carousel:(iCarousel *)carousel1 viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
        //create new view if no view is available for recycling
        CustomBusinessListingCell_iPad *businessListingView  = (CustomBusinessListingCell_iPad *)[[[NSBundle mainBundle]loadNibNamed:@"CustomBusinessListingCell_iPad" owner:self options:nil] objectAtIndex:0];
        businessListingView.frame =  CGRectMake(0, 0, LIST_VIEW_WIDTH, LIST_VIEW_HEIGHT);
        businessListingView.tag = index;
        businessListingView.lblBusinessName.verticalAlignment = BAVerticalAlignmentBottom;

        businessListingView.btnBook.tag = index;
        [businessListingView.btnBook addTarget:self action:@selector(btnBookClicked:) forControlEvents:UIControlEventTouchUpInside];
       
        businessListingView.btnBookmark.tag = index;
        [businessListingView.btnBookmark addTarget:self action:@selector(priceClicked:) forControlEvents:UIControlEventTouchUpInside];
       
         //NSLog(@"BusinessImage : %@",[[businessArr objectAtIndex:index] valueForKey:@"BusinessImage"]);
       
        [businessListingView setBusinessValue:[businessArr objectAtIndex:index]];
       
        if (index==[businessArr count]-1)
        {
            // ask next page only if we haven't reached last page
            if([businessArr count] < totalRecords)
            {
                if (!isLoadmore)
                {
                    isLoadmore = YES;
                    pageIndex = pageIndex+1;
                    [self loadNewData];
                }
            }
        }
        return businessListingView;
}

-(void)setCarouselPosition
{
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
    if ((orientation == UIInterfaceOrientationPortrait) || (orientation == UIInterfaceOrientationPortraitUpsideDown)) {
        [carousel scrollToOffset:0.6 duration:0.0];
    }
    else if((orientation == UIInterfaceOrientationLandscapeLeft) || (orientation == UIInterfaceOrientationLandscapeRight))
    {
        [carousel scrollToOffset:1.1 duration:0.0];
    }
}

- (CGFloat)carousel:(iCarousel *)_carousel valueForOption:(iCarouselOption)option withDefault:(CGFloat)value
{
    //customize carousel display
    switch (option)
    {
        case iCarouselOptionSpacing:
        {
            //add a bit of spacing between the item views
            return value * 1.08f;
        }
        case iCarouselOptionVisibleItems:
        {
            return 5;
        }
        default:
        {
            return value;
        }
    }
}

- (void)carouselDidEndScrollingAnimation:(iCarousel *)carousel1
{
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
    if ((orientation == UIInterfaceOrientationPortrait) || (orientation == UIInterfaceOrientationPortraitUpsideDown)) {
        if (carousel1.scrollOffset < 0.6) {
            [UIView beginAnimations:@"" context:nil];
            [UIView setAnimationDuration:0.7];
            [carousel1 scrollToOffset:0.6 duration:0.0];
            [UIView commitAnimations];
        }
    }
    else if ((orientation == UIInterfaceOrientationLandscapeLeft) || (orientation == UIInterfaceOrientationLandscapeRight))
    {
        if (carousel1.scrollOffset < 1.1) {
            [UIView beginAnimations:@"" context:nil];
            [UIView setAnimationDuration:0.7];
            [carousel1 scrollToOffset:1.1 duration:0.0];
            [UIView commitAnimations];
        }
    }
}

- (void)carouselDidEndDragging:(iCarousel *)carousel1 willDecelerate:(BOOL)decelerate
{
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
    if ((orientation == UIInterfaceOrientationPortrait) || (orientation == UIInterfaceOrientationPortraitUpsideDown)) {
        if (carousel1.scrollOffset < 0.6) {
            [UIView beginAnimations:@"" context:nil];
            [UIView setAnimationDuration:0.7];
            [carousel1 scrollToOffset:0.6 duration:0.0];
            [UIView commitAnimations];
        }
    }
    else if ((orientation == UIInterfaceOrientationLandscapeLeft) || (orientation == UIInterfaceOrientationLandscapeRight))
    {
        if (carousel1.scrollOffset < 1.1) {
            [UIView beginAnimations:@"" context:nil];
            [UIView setAnimationDuration:0.7];
            [carousel1 scrollToOffset:1.1 duration:0.0];
            [UIView commitAnimations];
        }
    }
}

Thanks,
Nilesh M. Prajapati

How to resolve apple's UDID issue for Push Notification in iPhone?

Hi,
Everyone,

Rumors say that Apple starts to prohibit the use of UDID in iOS applications from iOS 6.0 and onwards. You can use below solution for  < & >=  iOS 6.0 .

- The device token (used by APNS) and the UDID are two different things. They have nothing to do with each other.

- You obtain the device token for push notifications in your app delegate's application:didRegisterForRemoteNotificationsWithDeviceToken: method.


- The documentation notes the following:
The device token is different from the uniqueIdentifier property of UIDevice because, for security and privacy reasons, it must change when the device is wiped.


#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)

NSString *deviceID = nil;

#pragma mark -------------------
#pragma mark UIApplication methods
#pragma mark -------------------

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    if (![[NSUserDefaults standardUserDefaults] valueForKey:@"UUID"]) {
        if (SYSTEM_VERSION_LESS_THAN(@"6.0")) {
            self.deviceID = [[self GetUUID] retain];
        }
        else{
            NSUUID* udid= [UIDevice currentDevice].identifierForVendor;
            self.deviceID = [[udid UUIDString] retain];
        }
        [[NSUserDefaults standardUserDefaults] setValue:self.deviceID forKey:@"UUID"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    else{
        self.deviceID = [[[NSUserDefaults standardUserDefaults] valueForKey:@"UUID"] retain];
    }
}

#pragma mark -------------------
#pragma mark Push notification methods
#pragma mark -------------------

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    //NSLog(@"My token is: %@", deviceToken);
    NSString *devicetoken = [[[[deviceToken description]
                               stringByReplacingOccurrencesOfString:@"<"withString:@""]
                              stringByReplacingOccurrencesOfString:@">" withString:@""]
                             stringByReplacingOccurrencesOfString: @" " withString: @""];
    [self updateToken:devicetoken];
}

- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
    //NSLog(@"Failed to get token, error: %@", error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // get state
    UIApplicationState state=[application applicationState];
    if(state== UIApplicationStateActive)
        self.badgeCount=[[[userInfo valueForKey:@"aps"] valueForKey:@"badge"] intValue];
    else
        self.badgeCount= [UIApplication sharedApplication].applicationIconBadgeNumber;
}

- (NSString *)GetUUID
{
    CFUUIDRef theUUID = CFUUIDCreate(NULL);
    CFStringRef string = CFUUIDCreateString(NULL, theUUID);
    CFRelease(theUUID);
    return [(NSString *)string autorelease];
}

Thanks, 
Nilesh M. Prajapati

Monday, January 28, 2013

how to integrate barcode scanning in iphone?


Hi everyone,
Recently, I have worked with Barcode scanning project for iPhone/iPad development. It was good time for me to work on such project. So, I'm going to share information about that SDK.

SDK Name : ZXingObjC
SDK URL path : https://github.com/TheLevelUp/ZXingObjC

You need to add following frameworks in your projects to make it works.
For an iOS app:
  • AVFoundation.framework
  • CoreMedia.framework
  • CoreGraphics.framework
  • CoreVideo.framework
  • ImageIO.framework

Download the sdk and start to implement. if you find any difficulty then you can ask me.

Thanks,
Nilesh M. Prajapati

Wednesday, August 8, 2012

NSDateFormatter Example in iPhone SDK

Hi,
Every one,
I'm going to share NSDateFormatter examples for iPhone/iPad Applications. Please check below code reference :

+(NSString *)returnDateString:(NSDate *)date
{
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setFormatterBehavior:NSDateFormatterBehavior10_4];
    [formatter setDateFormat:@"dd/MM/yyyy"];
    NSLocale *usLocale = [NSLocale systemLocale];
    [formatter setLocale:usLocale];
    usLocale = nil;
    return [formatter stringFromDate:date];
}

+(NSString *)returnDateStringWithTime:(NSDate *)date
{
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setFormatterBehavior:NSDateFormatterBehavior10_4];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSLocale *usLocale = [NSLocale systemLocale];
    [formatter setLocale:usLocale];
    usLocale = nil;
    return [formatter stringFromDate:date];
}

+(NSDate *)returnFormattedStringWithDate:(NSString *)dateString
{
    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
       NSLocale *usLocale = [NSLocale systemLocale];
    [dateFormatter setLocale:usLocale];
    usLocale = nil;
    return [dateFormatter dateFromString:dateString];
}

Here is the list of the string formats that can be used with NSDateFormatter in iPhone/iPad Applications.

a: AM/PM
A: 0~86399999 (Millisecond of Day)

c/cc: 1~7 (Day of Week)
ccc: Sun/Mon/Tue/Wed/Thu/Fri/Sat
cccc: Sunday/Monday/Tuesday/Wednesday/Thursday/Friday/Saturday

d: 1~31 (0 padded Day of Month)
D: 1~366 (0 padded Day of Year)

e: 1~7 (0 padded Day of Week)
E~EEE: Sun/Mon/Tue/Wed/Thu/Fri/Sat
EEEE: Sunday/Monday/Tuesday/Wednesday/Thursday/Friday/Saturday

F: 1~5 (0 padded Week of Month, first day of week = Monday)

g: Julian Day Number (number of days since 4713 BC January 1)
G~GGG: BC/AD (Era Designator Abbreviated)
GGGG: Before Christ/Anno Domini

h: 1~12 (0 padded Hour (12hr))
H: 0~23 (0 padded Hour (24hr))

k: 1~24 (0 padded Hour (24hr)
K: 0~11 (0 padded Hour (12hr))

L/LL: 1~12 (0 padded Month)
LLL: Jan/Feb/Mar/Apr/May/Jun/Jul/Aug/Sep/Oct/Nov/Dec
LLLL: January/February/March/April/May/June/July/August/September/October/November/December

m: 0~59 (0 padded Minute)
M/MM: 1~12 (0 padded Month)
MMM: Jan/Feb/Mar/Apr/May/Jun/Jul/Aug/Sep/Oct/Nov/Dec
MMMM: January/February/March/April/May/June/July/August/September/October/November/December

q/qq: 1~4 (0 padded Quarter)
qqq: Q1/Q2/Q3/Q4
qqqq: 1st quarter/2nd quarter/3rd quarter/4th quarter
Q/QQ: 1~4 (0 padded Quarter)
QQQ: Q1/Q2/Q3/Q4
QQQQ: 1st quarter/2nd quarter/3rd quarter/4th quarter

s: 0~59 (0 padded Second)
S: (rounded Sub-Second)

u: (0 padded Year)

v~vvv: (General GMT Timezone Abbreviation)
vvvv: (General GMT Timezone Name)

w: 1~53 (0 padded Week of Year, 1st day of week = Sunday, NB: 1st week of year starts from the last Sunday of last year)
W: 1~5 (0 padded Week of Month, 1st day of week = Sunday)

y/yyyy: (Full Year)
yy/yyy: (2 Digits Year)
Y/YYYY: (Full Year, starting from the Sunday of the 1st week of year)
YY/YYY: (2 Digits Year, starting from the Sunday of the 1st week of year)

z~zzz: (Specific GMT Timezone Abbreviation)
zzzz: (Specific GMT Timezone Name)
Z: +0000 (RFC 822 Timezone)



Thanks & Regards,
Nilesh Prajapati

Wednesday, August 1, 2012

how to make custom tabbar in iphone?

Hello,
Just like as every time, I'm here to share code regarding "Custom Tabbar" in iPhone/iPad Application.

Please take a look..

Step 1:  Place these two files in to your project... "CustomTabBar.h" and "CustomTabBar.m"

#import <UIKit/UIKit.h>

@interface CustomTabBar : UITabBarController {
    UIButton *btn1;
    UIButton *btn2;
    UIButton *btn3;
    UIButton *btn4;
    UIButton *btn5;
}

@property (nonatomic, retain) UIButton *btn1;
@property (nonatomic, retain) UIButton *btn2;
@property (nonatomic, retain) UIButton *btn3;
@property (nonatomic, retain) UIButton *btn4;
@property (nonatomic, retain) UIButton *btn5;

-(void) hideTabBar;
-(void) addCustomElements;
-(void) selectTab:(int)tabID;

@end


#import "CustomTabBar.h"

@implementation CustomTabBar

@synthesize btn1, btn2, btn3, btn4, btn5;

- (void)viewDidAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self hideTabBar];
    [self addCustomElements];
}

-(void)hideTabBar
{
    for(UIView *view in self.view.subviews)
    {
        if([view isKindOfClass:[UITabBar class]])
        {
            view.hidden = YES;
            break;
        }
    }
}

-(void)hideNewTabBar
{
    self.btn1.hidden = 1;
    self.btn2.hidden = 1;
    self.btn3.hidden = 1;
    self.btn4.hidden = 1;
    self.btn5.hidden = 1;
}

- (void)showNewTabBar
{
    self.btn1.hidden = 0;
    self.btn2.hidden = 0;
    self.btn3.hidden = 0;
    self.btn4.hidden = 0;
    self.btn5.hidden = 0;
}

-(void)addCustomElements
{
    // Initialise our two images
    UIImage *btnImage = [UIImage imageNamed:@"NotificationsSelectedBg.png"];
    UIImage *btnImageSelected = [UIImage imageNamed:@"NavBar_01_s.png"];
   
    self.btn1 = [UIButton buttonWithType:UIButtonTypeCustom]; //Setup the button
    btn1.frame = CGRectMake(0, 430, 80, 50); // Set the frame (size and position) of the button)
    [btn1 setBackgroundImage:btnImage forState:UIControlStateNormal]; // Set the image for the normal state of the button
    [btn1 setBackgroundImage:btnImageSelected forState:UIControlStateSelected]; // Set the image for the selected state of the button
    [btn1 setTag:0]; // Assign the button a "tag" so when our "click" event is called we know which button was pressed.
    [btn1 setSelected:true]; // Set this button as selected (we will select the others to false as we only want Tab 1 to be selected initially
   
    // Now we repeat the process for the other buttons
    btnImage = [UIImage imageNamed:@"NotificationsSelectedBg.png"];
    btnImageSelected = [UIImage imageNamed:@"NavBar_02_s.png"];
    self.btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn2.frame = CGRectMake(80, 430, 80, 50);
    [btn2 setBackgroundImage:btnImage forState:UIControlStateNormal];
    [btn2 setBackgroundImage:btnImageSelected forState:UIControlStateSelected];
    [btn2 setTag:1];
   
    btnImage = [UIImage imageNamed:@"NotificationsSelectedBg.png"];
    btnImageSelected = [UIImage imageNamed:@"NavBar_03_s.png"];
    self.btn3 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn3.frame = CGRectMake(160, 430, 80, 50);
    [btn3 setBackgroundImage:btnImage forState:UIControlStateNormal];
    [btn3 setBackgroundImage:btnImageSelected forState:UIControlStateSelected];
    [btn3 setTag:2];
   
    btnImage = [UIImage imageNamed:@"NotificationsSelectedBg.png"];
    btnImageSelected = [UIImage imageNamed:@"NavBar_04_s.png"];
    self.btn4 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn4.frame = CGRectMake(240, 430, 80, 50);
    [btn4 setBackgroundImage:btnImage forState:UIControlStateNormal];
    [btn4 setBackgroundImage:btnImageSelected forState:UIControlStateSelected];
    [btn4 setTag:3];
   
    btnImage = [UIImage imageNamed:@"NotificationsSelectedBg.png"];
    btnImageSelected = [UIImage imageNamed:@"NavBar_04_s.png"];
    self.btn5 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn5.frame = CGRectMake(320, 430, 80, 50);
    [btn5 setBackgroundImage:btnImage forState:UIControlStateNormal];
    [btn5 setBackgroundImage:btnImageSelected forState:UIControlStateSelected];
    [btn5 setTag:4];
   
   
    // Add my new buttons to the view
    [self.view addSubview:btn1];
    [self.view addSubview:btn2];
    [self.view addSubview:btn3];
    [self.view addSubview:btn4];
    [self.view addSubview:btn5];

   
    // Setup event handlers so that the buttonClicked method will respond to the touch up inside event.
    [btn1 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [btn2 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [btn3 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [btn4 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [btn5 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)buttonClicked:(id)sender
{
    int tagNum = [sender tag];
    [self selectTab:tagNum];
}

- (void)selectTab:(int)tabID
{
    switch(tabID)
    {
        case 0:
            [btn1 setSelected:true];
            [btn2 setSelected:false];
            [btn3 setSelected:false];
            [btn4 setSelected:false];
            [btn5 setSelected:false];
            break;
        case 1:
            [btn1 setSelected:false];
            [btn2 setSelected:true];
            [btn3 setSelected:false];
            [btn4 setSelected:false];
            [btn5 setSelected:false];
            break;
        case 2:
            [btn1 setSelected:false];
            [btn2 setSelected:false];
            [btn3 setSelected:true];
            [btn4 setSelected:false];
            [btn5 setSelected:false];
            break;
        case 3:
            [btn1 setSelected:false];
            [btn2 setSelected:false];
            [btn3 setSelected:false];
            [btn4 setSelected:true];
            [btn5 setSelected:false];
            break;
        case 4:
            [btn1 setSelected:false];
            [btn2 setSelected:false];
            [btn3 setSelected:false];
            [btn4 setSelected:false];
            [btn5 setSelected:true];
            break;
    }   
    self.selectedIndex = tabID;
}

- (void)dealloc {
    [btn1 release];
    [btn2 release];
    [btn3 release];
    [btn4 release];
    [btn5 release];
    [super dealloc];
}

Step 2 :  If you user XIB base TabBarController then you need to set "CustomTabBar" as its class or otherwise you have to create TabBarController object of "CustomTabBar" class .

Now , you are able to use custom tabbar into user application. one more thing, You have to add the images which you want to assign at your tabbar controller items.

Thanks & Regards,
Nilesh Prajapati