Search This Blog

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






No comments:

Post a Comment