Search This Blog

Monday, 18 November 2013


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


REQUIREMENTS: Download SmallSockets Library from

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;

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 : 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.



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 …


[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 and Port to be 8801. Which makes our socket to be

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=@"";

sc = [Socket socket];
flag = TRUE;

if (flag == TRUE)

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

NSLog(@"Entered finally");
[sc close];


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 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.


-(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];


//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 is the 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 ;)

Tuesday, 12 February 2013

Custom Marker on MapView-iOS

Hello there,
          So here is a new one, how to place a custom marker on MapView in xcode:

its as simple as table view :

Override this following function in your .m file.Remeber to include MKMapViewDelegate in your .h file.

-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
        NSString *identifier = @"marker"; //identifier like we declare in tableview
    annotationV = [mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
        annotationV = [[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:identifier];
        annotationV.canShowCallout = YES;
        annotationV.image = [UIImage imageNamed:@"green_mark.png"];//using custom image for marker.
        annotationV.canShowCallout =NO;
        annotationV.rightCalloutAccessoryView =  [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    return annotationV;

Here what i am doing is using an image for marker,plus i am also displaying a banner above the marker for description.I am using "popup.png" image for banner.


Tuesday, 1 January 2013

send SMS via code - Blackberry

Hello friends,
                    Here is the simplest way to send an SMS from your app Blackberry. :)


String _no = "122344556767";
String _msg = "hello this is a test SMS.";
DatagramConnection _dc = null;
String _openString = "sms://";

_dc = (DatagramConnection);
byte[] data = _msg.getBytes();
Datagram d = _dc.newDatagram(_dc.getMaximumLength());

}catch(Exception e){


How to send Email from your app in Blackberry

Hello friends,
                     Here is the code for sending automated  email from your blackberry App :)


Message msg = new Message();
Address receipients[] = new Address[1];
receipients[0] = new Address("","user");//two paramters i .e email id and name.
msg.addRecipients(Message.RecipientType.TO, receipients);

msg.setSubject("Testing subject");
msg.setContent("This is a test mail.");

}catch(Exception e){

System.out.println("Error: "+e.toString());