在appdelegate中嘗試解決socket掉線問題

來源:互聯網
上載者:User

標籤:des   http   color   io   os   ar   strong   for   art   

#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(@" 收到推送訊息 : %@",[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]);

}

 

- (void)applicationWillResignActive:(UIApplication *)application

{

    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.

    // Use this method to 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"];

    

    //伺服器端推出登入;

    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(@"退出登入 %@",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(@"成功退出!");

        }

        

    }];

    [request setFailedBlock:^{

        NSError *error = [request error];

        NSLog(@"退出登入失敗 error is %@",error.description);

    }];

    [request startAsynchronous];

}

 

- (void)applicationDidEnterBackground:(UIApplication *)application

{

    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case 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 you can undo many of the changes made on entering the background.

}

 

- (void)applicationDidBecomeActive:(UIApplication *)application

{

    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was 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 is 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串連上伺服器

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

}

 

//發送心跳訊息

- (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關閉

- (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 收到伺服器發來的訊息

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

        

        //設定定時器向伺服器發送心跳訊息

        self.tickTimer = [NSTimer scheduledTimerWithTimeInterval:120 //秒

                                                          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 cancelButtonTitle:@"ok" otherButtonTitles:nil];

            //            [alert show];

            

            [[NSNotificationCenter defaultCenter] postNotificationName:@"AppReceiveNewMessage" object:message];

        }

    }

    else if([msgType isEqualToString:@"contact"])

    {

        [[NSNotificationCenter defaultCenter] postNotificationName:@"AppReceiveContact" object:message];

    }

}

 

@end

 

在appdelegate中嘗試解決socket掉線問題

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.