你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS webSocket之單利復雜完成即時通訊

iOS webSocket之單利復雜完成即時通訊

編輯:IOS開發綜合

1.pod 下載RACSRWebSocket


IOS webSocket之單利簡單實現即時通訊

2.添加包

Security.framework

Foundation.framework

C.network.framework

libicucore.A.tbd

libicucore.tbd


IOS webSocket之單利簡單實現即時通訊

3.創立單利

導入#import <SocketRocket/SRWebSocket.h>

.h中的辦法


IOS webSocket之單利簡單實現即時通訊

.m中的詳細完成 首先是 socket必需完成的代理辦法

-(void)webSocketDidOpen:(SRWebSocket *)webSocket{

NSLog(@"WebSocket DidOpen");

[webSocket send:jsonString];//翻開socket後依據後端要求傳入字典字符串

}


-(void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message{

//socket接納到信息後經過代理傳給內部運用

[self.delegate getMessageFromSocket:dic];

}


-(void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean{

NSLog(@"WebSocket closed");

}


-(void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error{

NSLog(@":( Websocket Failed With Error %@", error);

}

上面是幾個供內部調用的辦法

//由於URL不能夠是死的需求從接口中獲取,所以這個辦法用於在接口中拿到URL

- (void)WithIP:(NSString *)URLIP{

_webSocket.delegate = nil;

[_webSocket close];

NSString *urlStr = [NSString stringWithFormat:@"%@", URLIP];

NSURL *url = [NSURL URLWithString:urlStr];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

//如需更改鏈接的頭部則需此步

[request setValue:@"http://xxxxxx" forHTTPHeaderField:@"xxx"];

_webSocket = [[SRWebSocket alloc] initWithURLRequest:request];

_webSocket.delegate = self;

}


//拿到URL後可以翻開webSocket

- (void)openSocket {

[_webSocket open];

}


//加入頁面時記得封閉webSocket

- (void)closeSocket {

self.webSocket.delegate = nil;

[self.webSocket close];

self.webSocket = nil;

}


//內部聊天發送音訊給webSocket

- (void)sendTalkMessage:(NSString *)message{

NSMutableDictionary *dic = [NSMutableDictionary dictionary];

dic = [@{ @"content":message} mutableCopy];

[self sendMessage:dic];

}

4.在ViewController中調用

導入#import "webSocketManager.h"

創立單利

@property (nonatomic, strong) webSocketManager *webSocket;

上面是幾個次要的辦法運用

iOS webSocket之單利簡單實現即時通訊

感興味的可以詳細下載個demo看看,地址:

https://github.com/Flower0120/webSocketDemo.git


【iOS webSocket之單利復雜完成即時通訊】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved