#import <UIKit/UIKit.h>
#import "MainViewController.h"
#import "Reachability.h"
@interface Appdelegate:uiresponder <UIApplicationDelegate,SRWebSocketDelegate>
@property (Strong, nonatomic) UIWindow *window;
@property (nonatomic, ReadWrite) Srwebsocket *warblesocket;
@property (nonatomic, ReadWrite) BOOL Socketready;
@property (nonatomic) nstimer* Ticktimer;
-(void) connectchatserver;
-(void) disconnectchatserver;
-(void) sendmsg: (nsstring*) STRMSG;
@end
#import "AppDelegate.h"
#import "ASIHTTPRequest.h"
#import "MD5.h"
#import "ASIFormDataRequest.h"
#import "Comm.h"
#import "CBContact.h"
#import "EGODatabase.h"
#import "ChatMessage.h"
#import "InfoMessage.h"
#import "CBContact.h"
#import "MessageFrame.h"
#import "MessageCell.h"
#import "ASIHTTPRequest.h"
#import "SVProgressHUD.h"
#import "MD5.h"
#import "NoticeMessage.h"
#import "MyProfileTableViewController.h"
#import "ContactDetailTableViewController.h"
#import "ChatViewController.h"
#import "InfoViewController.h"
#import "NoticeViewController.h"
#import "ContactDetailTableViewController.h"
#import "ContactDetailViewController.h"
#import "Uicolor+extensions.h"
#import "Nsstring+pinyin.h"
#import "Comm.h"
#import <Crashlytics/Crashlytics.h>
@implementation Appdelegate
-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (nsdictionary *) launchOptions
{
Override point for customization after application launch.
Todo:connect to Socket.io Server
Load Server Configuration
Load Advertisement
Enabling keyboard Manager
Self.socketready = NO;
[Crashlytics startwithapikey:@ "9d0b0e078333459a3160c13c42d1d2bfab448df5"];
return YES;
}
-(void) Application: (UIApplication *) application Didregisterforremotenotificationswithdevicetoken: (NSData *) Devicetoken {
NSLog (@ "Devicetoken:%@", Devicetoken);
NSString *strdev = [[[[Devicetoken description] Stringbyreplacingoccurrencesofstring: @ "<" withstring: @ ""] Stringbyreplacingoccurrencesofstring: @ ">" withstring: @ "" Stringbyreplacingoccurrencesofstring: @ "" WithString: @""];
nsuserdefaults* defs = [Nsuserdefaults standarduserdefaults];
[Defs setvalue:strdev forkey:@ "Devicetoken"];
NSLog (@ "%@", Strdev);
}
-(void) Application: (UIApplication *) application Didfailtoregisterforremotenotificationswitherror: (NSError *) error {
NSLog (@ "Error in registration. Error:%@ ", error);
}
-(void) Application: (UIApplication *) application didreceiveremotenotification: (nsdictionary *) userInfo
{
NSLog (@ "received push message:%@", [[UserInfo objectforkey:@ "APS"] objectforkey:@ "alert"]);
}
-(void) Applicationwillresignactive: (uiapplication *) application
{
Sent when the application are about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as a incoming phone call or SMS message) or when the US Er quits the application and it begins the transition to the background state.
Use the This method to the pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
-(void) logoutwebserver
{
Nsuserdefaults *pref = [Nsuserdefaults standarduserdefaults];
[Pref setvalue:@ "" forkey:@ "pwd"];
Server-side launch login;
NSString *strtoken = [pref stringforkey:@ "Logintoken"];
NSString *strurl = [NSString stringwithformat:@ "%@/applogout?token=%@", Web_server_host,strtoken];
Nsurl *url = [Nsurl Urlwithstring:strurl];
__block asihttprequest *request = [ASIHTTPRequest Requestwithurl:url];
[Request setcompletionblock:^{
NSString *responsestring = [request responsestring];
NSLog (@ "Exit login%@", responsestring);
Nserror *error = nil;
NSData *jsondata = [responsestring datausingencoding:nsutf8stringencoding];
Nsdictionary *dict = [nsjsonserialization jsonobjectwithdata:jsondata options:kniloptions error:&error];
NSString *msgcode = [dict objectforkey:@ "Code"];
if ([Msgcode isequaltostring:@ "200"]) {
NSLog (@ "Successful exit!");
}
}];
[Request setfailedblock:^{
Nserror *error = [request ERROR];
NSLog (@ "Log out failed" error is%@ ", error.description);
}];
[Request startasynchronous];
}
-(void) Applicationdidenterbackground: (uiapplication *) application
{
Use the This method to release the shared resources, save user data, invalidate timers, and store enough application state info Rmation to the restore your application to the it is terminated later.
If your application supports background execution, this method is called instead of Applicationwillterminate:when the User quits.
[[Nsnotificationcenter Defaultcenter] postnotificationname:@ "Appdisconnectchatserver" object:nil];
[Self disconnectchatserver];
[Self logoutwebserver];
}
-(void) Applicationwillenterforeground: (uiapplication *) application
{
Called as part of the transition from the background to the inactive state; Here's can undo many of the changes made on entering the background.
}
-(void) Applicationdidbecomeactive: (uiapplication *) application
{
Restart any tasks this were paused (or not yet started) while the application is inactive. If the application is previously in the background, optionally refresh the user interface.
[[UIApplication Sharedapplication] registerforremotenotificationtypes: (Uiremotenotificationtypebadge | Uiremotenotificationtypesound | Uiremotenotificationtypealert)];
[UIApplication sharedapplication].applicationiconbadgenumber = 0;
Nsuserdefaults *pref = [Nsuserdefaults standarduserdefaults];
nsstring* struid = [pref stringforkey:@ "UID"];
nsstring* strpwd = [pref stringforkey:@ "pwd"];
if (!struid | |!strpwd | | [Struid isequaltostring:@ ""] | | [Strpwd isequaltostring:@ ""]) {
Return
}
Else
{
[Self connectchatserver];
[[Nsnotificationcenter Defaultcenter] postnotificationname:@ "Applogin" object:nil];
}
}
-(void) Applicationwillterminate: (uiapplication *) application
{
Called when the application are about to terminate. Save data if appropriate. See also Applicationdidenterbackground:.
}
-(void) reconnectchatserver
{
NSLog (@ "Reconnect to chat server ...");
if (Self.socketready = = NO) {
Nsuserdefaults *pref = [Nsuserdefaults standarduserdefaults];
nsstring* struid = [pref stringforkey:@ "UID"];
nsstring* strpwd = [pref stringforkey:@ "pwd"];
if (![ Struid isequaltostring:@ "" &&! [Strpwd isequaltostring:@ ""]) {
Self.warblesocket = [[Srwebsocket alloc] Initwithurl:[[nsurl alloc] initwithstring:chat_server_host]];
Self.warbleSocket.delegate = self;
[Self.warblesocket Open];
}
[Self performselector: @selector (reconnectchatserver) Withobject:nil afterdelay:10.0];
}
}
-(void) connectchatserver
{
NSLog (@ "Connect to chat server ...");
if (Self.socketready = = NO) {
Self.warblesocket = [[Srwebsocket alloc] Initwithurl:[[nsurl alloc] initwithstring:chat_server_host]];
Self.warbleSocket.delegate = self;
[Self.warblesocket Open];
// }
}
-(void) disconnectchatserver
{
NSLog (@ "Disconnect from Chat server ...");
[Self.warblesocket Close];
}
-(void) sendmsg: (nsstring*) STRMSG
{
[Self.warblesocket send:strmsg];
}
WebSocket connecting to the server
-(void) Websocketdidopen: (Srwebsocket *) webSocket
{
Self.socketready = YES;
Nsuserdefaults *pref = [Nsuserdefaults standarduserdefaults];
nsstring* struid = [pref stringforkey:@ "UID"];
nsstring* strpwd = [pref stringforkey:@ "pwd"];
nsstring* strlogin = [NSString stringwithformat:@ "{\" type\ ": \" login\ ", \" uid\ ": \"%@\ ", \" pwd\ ": \"%@\ "}", Struid, STRPWD];
[Self.warblesocket Send:strlogin];
}
Send Heartbeat message
-(void) Timechange: (nstimer*) Thetimer
{
if (Self.socketready) {
Nsuserdefaults *pref = [Nsuserdefaults standarduserdefaults];
nsstring* struid = [pref stringforkey:@ "UID"];
nsstring* strpwd = [pref stringforkey:@ "pwd"];
NSString *strmsg = [NSString stringwithformat:@ "{\" type\ ": \" chat\ ", \" from\ ": \"%@\ ", \" to\ ": \"%@\ ", \" msg\ ": \"%@\ "}", struid,struid,@ ""];
[Self.warblesocket send:strmsg];
}
}
WebSocket off
-(void) WebSocket: (Srwebsocket *) webSocket Didclosewithcode: (nsinteger) code reason: (NSString *) reason Wasclean: (BOOL ) Wasclean
{
Self.socketready = NO;
[Self.ticktimer invalidate];
NSLog (@ "Disconnect from chat server [OK]");
[Self performselector: @selector (reconnectchatserver) Withobject:nil afterdelay:10.0];
}
Srwebsocket received a message from the server
-(void) WebSocket: (Srwebsocket *) WebSocket didreceivemessage: (ID) message
{
NSString *receivedata = (NSString *) message;
NSLog (@ "Receive node message:%@", Receivedata);
Nserror *error = nil;
NSData *jsondata = [Receivedata datausingencoding:nsutf8stringencoding];
Nsdictionary *dict = [nsjsonserialization jsonobjectwithdata:jsondata options:kniloptions error:&error];
nsstring* Msgtype = [dict objectforkey:@ "type"];
NSLog (@ "Msgtype is%@", msgtype);
if ([Msgtype isequaltostring:@ "Login"])
{
nsstring* token = [dict objectforkey:@ "token"];
Nsuserdefaults *pref = [Nsuserdefaults standarduserdefaults];
[Pref setvalue:token forkey:@ "token"];
[Self.ticktimer invalidate];
Set a timer to send a heartbeat message to the server
Self.ticktimer = [Nstimer scheduledtimerwithtimeinterval:120//sec
Target:self
Selector: @selector (timechange:)
Userinfo:nil
Repeats:yes];
[Self.ticktimer fire];
NSLog (@ "Connect chat server [OK]");
}
else if ([Msgtype isequaltostring:@ "info"])
{
[[Nsnotificationcenter Defaultcenter] postnotificationname:@ "Appreceiveinfo" object:message];
}
else if ([Msgtype isequaltostring:@ "notice"])
{
[[Nsnotificationcenter Defaultcenter] postnotificationname:@ "Appreceivenotice" object:message];
noticemessage* msg = [[Noticemessage alloc] init];
Nsdictionary *d = [dict objectforkey:@ "MSG"];
Msg.strtitle = [D objectforkey:@ "title"];
Msg.strcontent = [D objectforkey:@ "content"];
Msg.strdate = [D objectforkey:@ "date"];
//
[Arraynotice addobject:msg];
}
else if ([Msgtype isequaltostring:@ "chat"])
{
nsstring* content = [dict objectforkey:@ "MSG"];
if (![ Content isequaltostring:@ ""]) {
Uialertview *alert = [[Uialertview alloc]initwithtitle:@ "msg" Message:content delegate:self cancelButtonTitl e:@ "OK" otherbuttontitles:nil];
[Alert show];
[[Nsnotificationcenter Defaultcenter] postnotificationname:@ "Appreceivenewmessage" object:message];
}
}
else if ([Msgtype isequaltostring:@ "Contact"])
{
[[Nsnotificationcenter Defaultcenter] postnotificationname:@ "Appreceivecontact" object:message];
}
}
@end
Try to solve the socket drop problem in appdelegate