SignalR
一、百度可知:ASP.NET SignalR 是为 ASP.NET 开发人员提供的一个库,可以简化开发人员将实时 Web 功能添加到应用程序的过程。实时 Web 功能是指这样一种功能:当所连接的客户端变得可用时服务器代码可以立即向其推送内容,而不是让服务器等待客户端请求新的数据。
二、现在我们在iOS客户端利用SignalR建立长连接。开源库
- pod 'SwiftSignalRClient'
2.在OC项目中新建swift文件,创建桥接文件,然后在项目中
#import "TestDemo-Swift.h"//TestDemo为项目名称
3.因为SwiftSignalRClient没有做OC的支持,所以这里封装一层来支持OC
import Foundation
import SwiftSignalRClient
//SignalR的返回值都需要遵守codeble协议,不能用Any、AnyObject,所以这里声明一个结构体接收
struct ParamData:Codable {
var Id: String?
var UserId: Int?
var NiceName: String?
var Time: Int?
var DataType: String?
var JsonData: String?
var OrganizationCode: String?
var CustomerId: Int?
}
@objc public protocol XFSignalRClientDelegate : class {
func clientDidConnectSuccess(client: XFSignalRClient)
func clientDidConnectFailed(client: XFSignalRClient, error: Error)
func clientDidClosed(client: XFSignalRClient, error: Error?)
}
@objcMembers public class XFSignalRClient : NSObject {
var url: String?
var headers: [String: String]?
var PlatUserId: [String: Int]?
private var connection: HubConnection?
public weak var delegate: XFSignalRClientDelegate?
private override init() {
super.init()
}
static let swiftSharedInstance = XFSignalRClient()//写一个管理单例
//在oc中这样写才能被调用
@objc open class func sharedInstance() -> XFSignalRClient
{
return swiftSharedInstance
}
public func start() {
if (self.connection != nil) {
return
}
self.connection = HubConnectionBuilder(url: URL(string: self.url!)!)
.withAutoReconnect()//添加了自动重连
.withLogging(minLogLevel: .debug)
.withHttpConnectionOptions(configureHttpOptions: { (httpConnectionOptions) in
if let header = self.headers {
for (key, value) in header {
httpConnectionOptions.headers[key] = value
}
}
})
.build()
self.connection?.delegate = self
}
public func stop() {
if (self.connection == nil) {
return
}
self.connection?.stop()
}
//注册服务器方法,在block中接收数据
public func on(method: String, callback: @escaping (_ meg: XFSignalRModel?) -> Void) {
self.connection?.on(method: method, callback: { (argumentExtractor) in
let data = try argumentExtractor .getArgument(type: ParamData.self);
let model:XFSignalRModel = XFSignalRModel()
model.UserId = String(data.UserId!)
model.JsonData = data.JsonData
model.DataType = data.DataType
model.Id = data.Id
callback(model)//这里的model是另外写了一个遵循codable协议的类,在OC中调用
})
self.connection?.start()//注册服务器方法后才能start(),不然无法收到数据
}
//添加到组的方法,连接成功后,需要添加到组才能接收到数据
public func invoke(method: String, invocationDidComplete: @escaping (_ error: Error?) -> Void) {
//具体参数和服务端协商
self.connection?.invoke(method: method, arguments: [self.PlatUserId], invocationDidComplete: invocationDidComplete)
}
}
extension XFSignalRClient: HubConnectionDelegate {
public func connectionDidOpen(hubConnection: HubConnection) {
self.delegate?.clientDidConnectSuccess(client: self)
}
public func connectionDidFailToOpen(error: Error) {
self.delegate?.clientDidConnectFailed(client: self, error: error)
}
public func connectionDidClose(error: Error?) {
self.delegate?.clientDidClosed(client: self, error: error)
}
public func connectionWillReconnect(error: Error) {
print("开始重新连接")
}
public func connectionDidReconnect() {
print("重连成功")
self.delegate?.clientDidConnectSuccess(client: self) //重新连接后需要重新加入组才能收到消息
}
}
4.OC中调用
NSString *pushUrl = @"http://xxxxxx;
int GuardianId = 32323;
NSDictionary *paramDic = @{@"PlatUserId":@(GuardianId)};
[XFSignalRClient swiftSharedInstance].url = pushUrl;
[XFSignalRClient swiftSharedInstance].PlatUserId = paramDic;
[XFSignalRClient swiftSharedInstance].delegate = self;
[[XFSignalRClient swiftSharedInstance] start];
[[XFSignalRClient swiftSharedInstance] onMethod:@"ReciveSaasMessage" callback:^(XFSignalRModel * _Nullable model) {
//处理数据
}];
在连接成功的代理中调用加入组的方法
- (void)clientDidConnectSuccessWithClient:(XFSignalRClient *)client {
[client invokeWithMethod:@"AddToGroup" invocationDidComplete:^(NSError * _Nullable error) {
if (error) {
NSLog(@"error %@",error);
}
}];
}
好了,这样就可以接收数据了。要是有什么不对的地方欢迎指正。
参考博客//www.greatytc.com/p/8c9d18511df2