Search This Blog

Loading...

Monday, 7 April 2014

Unzip File -iOS

Hello,

So , after a long research i found nothing which can unzip the zip file with subfolders and other files.So i am providing you a function which will do the job. Also, i assume you can setup the Objective-zip Library very well,for those who don't have the idea here is the link for tutorial and here is the link to download.


Below is the code , which is self explanatory, you just need your zip file Document directory root.


-(void)UnzipFile{
   
    NSArray *dirPaths;
    NSString *docsDir;
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    docsDir = [dirPaths objectAtIndex:0];
    NSString *soundFilePath = [docsDir
                               stringByAppendingPathComponent:[NSString stringWithFormat:@"Facility Manual.zip"]];
   
    ZipFile *zipF = [[ZipFile alloc]initWithFileName:soundFilePath mode:ZipFileModeUnzip];
    //Listing all files in zip file
   
    NSArray *infos = [zipF listFileInZipInfos];
    [loadingView setHidden:NO];
    bytesReceived.text  = @"Unzipping Files";
    [progress setHidden:YES];
    for(FileInZipInfo *fileInfo in infos){
       
        //Identifying if file in Zip is a folder or pdf
        NSRange range = [fileInfo.name rangeOfString:@".pdf" options:NSCaseInsensitiveSearch];
        if(range.length>0){
           
        //File found in zip locating the file in zip file
        [zipF locateFileInZip:fileInfo.name];
       
        //Read Stream reading current File in zip file
        ZipReadStream *readStream = [zipF readCurrentFileInZip];
       
        //Initializing and declaring buffer to read the data from zip file for current file
        NSMutableData *data = [[NSMutableData alloc]initWithLength:256];
       
        //Parsing the Name provided by zip file to get the file name
        NSArray *bits = [fileInfo.name componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"/"]];
           
        //Building file path on local Drive where it will be unzipped.
        NSString *documentdir;
        NSArray *documentPaths;
         
        documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        documentdir = [documentPaths objectAtIndex:0];
           
        //Final path of file in local drive
        NSString *yoyoDir = [documentdir stringByAppendingPathComponent:[NSString stringWithFormat:@"All Files/%@",[bits objectAtIndex:bits.count-1] ]];
           
        //File Manager creating the file in local drive
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager createFileAtPath:yoyoDir contents:nil attributes:nil];
           
        //Writing data in file created on Local Drive
        NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:yoyoDir];
           
            do{
                //Reset Buffer
                [data setLength:256];
               
                int bytesRead = [readStream readDataWithBuffer:data];
                if(bytesRead>0){
                    [data setLength:bytesRead];
                        [fileHandle writeData:data];
                }else{
                    break;
                }
               

            }while(YES);
        //Releasing buffer and FileManager
        [fileHandle closeFile];
        fileManager = nil;
        data = nil;
           
        //Finishing the Read Stream reading.
        [readStream finishedReading];
        }
    }

    //Close the zipFile prevents from corrupt zip.
    [zipF close];
   
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    [fileMgr removeItemAtPath:soundFilePath error:NULL];
    [loadingView setHidden:YES];
   
}


Happy Programming ... ;)

Sunday, 23 March 2014

Notification issue -iOS

Hello Friends,

Seems  like Apple is not serious with there job ... ;) , i found another bug in iOS 7 , what happened was i triggered a local notification from my app only when my app is in background , local notification has Sound file which is supposed to be played when notification is delivered to user. And WHOA, when user taps on local notification and app becomes active, local notification sound kept on playing whereas it was supposed to be stopped. Then with little R&D , i found that this issue is with iOS 7 only and its working fine for previous versions.

       So enough talks ... phewww ...here is the function to fix this issue


//Fix Local Notification sound issue for iOS 7
- (void)fixLocalNotificationforiOS7{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
        [[UIApplication sharedApplication] setApplicationIconBadgeNumber: 1];
        [[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
    }
}



Happy programming... :)

CHAO...Signing out...

Tuesday, 11 March 2014

UITextView issue -iOS

Hello Friends,

                So here is another thing coming in iOS7 which may annoy you some day today or later....in iOS7 , if you guys noted or not your UITextView clips last line out of view. Try this thing tap on return until you reach end of UITextView bounds now again tap return and start typing ....voila where is the text !!!

             Actually it gets clipped , i am not sure if it is a bug or apple did this intentionally. But, the bottom line is  " It's Annoying" . Yesterday i wasted 2 hours to solve this issue :P

           And here is the code which may handle this thing at some extent.

NOTE: This code will clip the last line on tapping return , but as soon as user starts typing characters the line becomes visible :)


STEP 1: I assume you are using UITextViewDelegate in your view controller.

STEP 2: Simply over ride this below delegate function in your view controller.


-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
   
   [textView scrollRangeToVisible:range];
    return YES;
}


I am simply trying to autoscroll the textview to make the range visible. I think its the easiest way to cope with it , until apple sort out this thing :)


Happy Programming!
CHAO

Wednesday, 5 February 2014

AVAudioPlayer issue -iOS

Hello All,

Today i found a strange behaviour of AVAudioPlayer in my app, i never set any property for microphone output or anything , and also i have multiple players on different View Controllers. But on one of them the Audio Output was played through Microphone instead of Speakers.

       So here is a simple code to route audio to speakers if its coming from Microphone using AVAudioPlayer.

Simple copy and Paste this below code in your : -(void)viewDidLoad; method:

 [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
    AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &audioRouteOverride);


Hope this helps some one someday, can save your day ;)

CHAO

Happy Programming.

Monday, 18 November 2013

Sockets-iOS


TITLE:Sending raw data over a Socket from your iOS app.


LEVEL: INTERMEDIATE


REQUIREMENTS: Download SmallSockets Library from http://smallsockets.sourceforge.net/


DESCRIPTION:This tutorial will explain, how to write data from iOS app on your server socket. Socket as by mean are best when it comes to performance, and security.
Transmission over Sockets are fast and this is the reason sockets are used for live media streaming, chat servers etc.



WHY THIS METHOD? - As many of you were thinking why Sockets? When we have XML Soap API's, JSON Post API's , JSON Get API's . The Difference lies here, all these methods I mentioned are not a good option when you want to send data in background or you want best performance from your app, as sockets are the fastest medium of communication with servers.


So , In this tutorial we will send raw text data to server.




STEP 1(Creating new Project): Create a new project in xcode, select 'Single View controller' as a template.









 







Now, on next step, enter a name for your project , organization name, company identifier and Device for which you want to build an app. As shown below in screenshot, you need to enable ARC and Mainstoryboards. Benefit of using ARC in your project is that xcode auto manages the memory allocation and release. As a common error we mostly counter is regarding memory allocations, so this will prevent such error's and manage the memory allocation for you. Secondly, using MainStoryboards in your project reduce the written code by noticeable margin , and also provides you a single place to maintain all your View Controllers. One thing that must be noticed here is that you need not to use any Navigation controller when using Mainstoryboards.

















STEP 2: Now, review the left navigation panel, you should have an AppDelegate.h , AppDelegate.m ,ViewController.h , ViewController.m and MainStoryboard.storyboard files.

















I assume that you know what these files are, for a brief AppDelegate is an instance of your application. ViewController is self explanatory. Mainstoryboard.storyboard is your place where all the ViewControllers will be managed.


STEP 3: With this, we are up with setting up a new project and ready to do some code :)



In your AppDelegate.h file declare a function as below...


-(void)sendData:(NSString *)rawText;




Now let's make some UI , as of this example I am giving a TextField and one button namely 'Send' .


Open Mainstoryboard.storyboard file ,as you will see that MainStoryboard already has one ViewController by default, this ViewController is associated with your ViewController class, add a buttons and a TextField to ViewController as shown below.




 











Now , next is to create IBOutlet's for these two UIElements added in our ViewController. For this go to ViewController.h and replace your code with the following code...



#import <UIKit/UIKit.h>


@interface ViewController : UIViewController<UITextFieldDelegate>{

IBOutlet UIButton *sendBtn;
IBOutlet UITextField *rawText;
}
@property(retain,nonatomic)IBOutlet UIButton *sendBtn;
@property(retain,nonatomic)IBOutlet UITextField *rawText;
-(IBAction)buttonPressed:(id)sender;
@end


Synthesize these IBOutlet's in ViewController.m file as below...


@synthesize sendBtn,rawText;


If you see in above code , we declared IBOutlet's for UIElements set property for these IBOutlet's , included the UITextFieldDelegate in our project, and , also we declared a function to handle the click events of button.


Now we need to link these IBOutlet's and touch event IBAction with UIElement's, as shown below...





 
 











I assume that you very well know the procedure to link IBOutlet's with UIElements, so link the delegate method of TextField with ViewController class ,IBOutlet's and IBAction with button.


With this we are ready to roll :)


STEP 5: Till now, we are up with an app having three UIElements , which will be displayed to user and from where user will enter the text in texfield and tap on send button, on tapping send button device will send the text entered in textfield to server through a socket.


So for those who don't know about sockets I just want to give brief explanation , a socket is a combination of IP address and PORT on server (for example : 122.122.1.0:9904).Socket is one end-point of a two-way communication link between two programs running on the network.






So let's start with some code, first of all we need to add SmallSocket library to our project for this, just is drag and drop the following files from SmallSocket Library to your project.





1.AbstractSocket.h

2.AbstractSocket.m
3.Socket.h
4.Socket.m

As we are using ARC in our project we will need to add a compiler flag for these files, as these files are non ARC.



For this, follow the instructions below:


Adding Compiler Flag for Non-ARC classes:


Go to project's build phase, and expand 'Compile Sources', you will see these files listed here, if not add these files by click on '+' button in bottom of list.Now add a compiler flag '-fno-objc-arc' as shown in screenshot below...





 











That's All let's come back to project now...



We will code the IBAction of send button, we added in our ViewController. For this, go to ViewController.m file and add this below function …


-(IBAction)buttonPressed:(id)sender{

if(sender==sendBtn){
if(rawData.text.length>0){
[app sendData:rawData.text];
}

}
}



If you remember we declared this function in AppDelegate.h file in Step 3, we are simply calling that function in IBAction described above, and passing the text entered by user as a parameter to that function.




STEP 6: I am no good in writing such big tutorial's :p , but we are almost done. Now, we are left with actual functionality which will send data on server using socket. For this example I am assuming an IP Address 134.12.112.64 and Port to be 8801. Which makes our socket to be 134.12.112.64:8801.





So,now, Import AbstractSocket.h and Socket.h in AppDelegate.m..


#import "Socket.h"
#import "AbstractSocket.h"


Now open your AppDelegate.m file, and add below functions , that we declared in AppDelegate.h file...


-(void)sendData:(NSString *)rawText{
Socket * sc;
int port = 8801;
NSString * strhost=@"134.12.112.64";

sc = [Socket socket];
flag = TRUE;

@try
{
if (flag == TRUE)
{

[sc connectToHostName:strhost port:port];
[sc writeString:rawText];
NSLog(@"Value of socket %@",sc);
//[sc close];
//sc=nil;
}
flag = FALSE;
}
@catch (NSException *exception)
{
NSLog(@"Error %@",exception);
NSString * string2 = [NSString stringWithFormat:@"Error for exception %@",[exception reason]];
NSLog(@"value of %@ ",string2);
[sc close];
sc=nil;

}
@finally
{
NSLog(@"Entered finally");
[sc close];
sc=nil;
}


}




That's it , now you just need to add a property in project's info.plist as shown below to make it work in background....


In below screenshot , we are setting a property which tells iOS that our app will keep running in background.


That's all run your app , and it will start sending GPS info on click of start button, you will need to code a listener on server end whether in PHP or ASP.NET which will receive , parse and store the data sent by app on socket.You can send an image in bytes, or a video in bytes or anything over the socket....


Happy Programming... :)






Friday, 21 June 2013

Drastic Floods in uttrakhand

Hello All,

I am very sad today coz of such a drastic floods in uttrakhand.Its we who are responsible for such natural disaster,mother nature told us that she is the master of this world,and we are annoying her by our activities of creating concrete jungles and deforestation.WE really need to take this matter seriously,as this shows that if we dont stop ,the day will come when this beautiful world made by mother nature will be destroyed by mother nature itself.

I pray for the victims who lost there lives ,there families in this drastic mishappening:






And a grand salute to our defence forces ,who really showed there courage and proves wy they are the world's 3rd largest army,and most skilled commandoes.Inidan AirForce , Indian Army took the rescue operation in there hands,and in worst weather condition they reached to the places that were totally cut-off from the country.   I AM PROUD TO BE A PART OF SUCH COUNTRY .......

Friday, 10 May 2013

Text file-iOS

Hello friends,

Here i am with something different not new....how to read a text from text file or rtf file and display the text in UITextView , UILabel or UITextField....Whichever you like...


For this simple example , i want you to first drag and drop a txt or rtf file into your project in xcode.

Then simply do the following:

NSString* filePath = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"txt"];
//type may change as per the format of your file in our case it can be txt or rtf
 depending on the extension of your file.
 
Next do the following:
 
NSString *myText = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil]; 
 

You can pass this 'myText' to your UI Element 'text' property.


That's it you are done :)


Wednesday, 24 April 2013

First look of SMUFFY

Hello Friends,

Sorry for being away for long time, i was going through a big change in life.Recently shifted my job and now working with tycoons,already excited to work with them.

For you to get excited here is the first look of my own iphone app......just gueess what it can be ;)





This will make you stick with your iPhone......lot of features in just one app,ssshhhhhh right now i can't share you what it has....wait for the BANG!!!

Thursday, 28 February 2013

Number validation-iOS

Hello there,
         Here is the simple thing how to put validation for numbers only in xcode.This example is for contacts ,and will also include '+' ,in validation.


Function:

-(BOOL)numberValidation:(NSString *)number{
   
   
    NSCharacterSet *decimalSet = [NSCharacterSet decimalDigitCharacterSet];
    BOOL stringIsValid = ([[number stringByTrimmingCharactersInSet:decimalSet] isEqualToString:@""] ||
                          [[number stringByTrimmingCharactersInSet:decimalSet] isEqualToString:@"+"]);
    return stringIsValid;
}



Example for how to use:

Suppose you have a UITextField IBOutlet 'abc'

so do it like this:

BOOL check = [self numberValidation:abc.text];

if(!check){

//show alert view ,when validation fails.

}


Happy Programming ;)

Thursday, 14 February 2013

Long Gesture-iOS

Hello friends ,
      So here is something from old school......hehehe.......we still have lot of useful things from old school.What if you are working on xcode project using MainStoryBoard??? and you want to capture the long press on button??? ...dont know ?......awww dont be sad ...here is the code..


CODE:

first add a gesture recognizer,as i am doing below,suppose you have an IBOutlet 'btnEmergencyBeacon' for UIButton.Then in your view did load method ,do this :

  UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    [self.btnEmergencyBeacon addGestureRecognizer:longPress];



Now simply override this function , in your same .m file :

- (void)longPress:(UILongPressGestureRecognizer*)gesture {
    if ( gesture.state == UIGestureRecognizerStateEnded ) {
       //Do something on long press....for example ill code for UIAlertView.

        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Demo" message:@"Long Press Countered" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
}


thats all,you can add this gesture recognizer to some view or anything else....


Happy programming ;)