Swift Socket连接

1,744 阅读2分钟

代码基于 Swift SignalR Client for Asp.Net Core SignalR server 链接:github.com/moozzyk/Sig…

  • 导入三方库
  • 封装方法
  • 如何与OC桥接代码
  • 代码调用示例
  • 结束

导入三方库

use_frameworks!
pod 'SwiftSignalRClient'

封装方法

import UIKit;
import SwiftSignalRClient

//返回值是一个函数指针,入参为String 返回值也是String
typealias funcBlock = (String) -> ()
//typealias errorBlock = (String,Error?) -> ()
@objc class SignalRSwift: NSObject {
    
    private let dispatchQueue = DispatchQueue(label: "hubsamplephone.queue.dispatcheueuq")
    
    private var chatHubConnection: HubConnection?
    private var chatHubConnectionDelegate: HubConnectionDelegate?
    private var name = ""
    private var messages: [String] = []
    
    @objc public func signalROpen(url:String,headers: [String: String]?,hubName:String,blockfunc:funcBlock!){
        name=hubName
        self.chatHubConnectionDelegate = ChatHubConnectionDelegate(signalrswift: self)
        self.chatHubConnection = HubConnectionBuilder(url: URL(string: url)!)
            .withLogging(minLogLevel: .debug)
            .withHubConnectionDelegate(delegate: self.chatHubConnectionDelegate!)
            .withHttpConnectionOptions(configureHttpOptions: { (httpConnectionOptions) in
                if let header = headers {
                    for (key, value) in header {
                        httpConnectionOptions.headers[key] = value
                    }
                }
            })
            .build()
        
        self.chatHubConnection!.on(method: "Message", callback: {(message: String) in
            //            self.appendMessage(message: "\(message)")
             blockfunc(message)
        })
        self.chatHubConnection!.start()
    }
    @objc public func signalRClose(){
        chatHubConnection?.stop()
    }
    
    @objc public func sendMessage(message:String,arg:Array<String>, invocationDidComplete: @escaping (_ result: AnyObject?, _ error: Error?) -> Void) {
        if message != "" {
//            chatHubConnection?.invoke(method:"SendMessage",message) { error in
////                if let e = error {
////                    self.appendMessage(message: "Error: \(e)")
////                }
//            }
//
            chatHubConnection?.invoke(method: "add", arg, resultType:Int.self, invocationDidComplete: { result, error in
                if let error = error {
                       print("error: \(error)")
                   } else {
                       print("Add result: \(result!)")
                   }
            })
        }
    }
    //连接是否打开
    fileprivate func connectionDidOpen() {
//        chatHubConnection?.invoke(method:"Join", name) { error in
////            if let e = error {
////                self.appendMessage(message: "Error: \(e)";
////            }
//        }
        print("=============连接是否成功==============")
    }
    //连接是否失败
    fileprivate func connectionDidFailToOpen(error: Error) {
        blockUI(message: "Connection failed to start.", error: error)
        print("=============连接是否失败==============")
    }
    //连接是否关闭
    fileprivate func connectionDidClose(error: Error?) {
        print("=============连接是否关闭==============")
        blockUI(message: "Connection is closed.", error: error)
    }
    //连接将重新连接
    fileprivate func connectionWillReconnect(error: Error?) {
        print("=============连接将重新连接==============")
    }
    //连接是否重新连接
    fileprivate func connectionDidReconnect() {
        print("=============连接是否重新连接==============")
    }
    
    func blockUI(message: String, error: Error?) {
        var message = message
        if let e = error {
            message.append(" Error: \(e)")
        }
//                appendMessage(message: message)
//                toggleUI(isEnabled: false)
    }
}

class ChatHubConnectionDelegate: HubConnectionDelegate {
    
    weak var signalrswift: SignalRSwift?
    
    init(signalrswift: SignalRSwift) {
        self.signalrswift = signalrswift
    }
    
    func connectionDidOpen(hubConnection: HubConnection) {
        signalrswift?.connectionDidOpen()
    }
    
    func connectionDidFailToOpen(error: Error) {
        signalrswift?.connectionDidFailToOpen(error: error)
    }
    
    func connectionDidClose(error: Error?) {
        signalrswift?.connectionDidClose(error: error)
    }
    
    func connectionWillReconnect(error: Error) {
        signalrswift?.connectionWillReconnect(error: error)
    }
    
    func connectionDidReconnect() {
        signalrswift?.connectionDidReconnect()
    }
}



如何与OC桥接

导入OC带入SWift文件会自动生成桥接文件 这时候直接点击确认生成即可 

1. SignalR-ObjC-Bridge-Swift-Bridging-Header
2. Enable Bitcode  设置成YES
3. 桥接代码时候一定写完之后运行一下不然生成不了.h方法

代码调用示例

  //打开signalR
    NSString * token = @"xxx";
    signalrSwift=[[SignalRSwift alloc]init];
    NSString *signalRString =@"xxxx";
    NSDictionary *headers = @{@"Authorization":token,@"Content-Type":@"application/json"};
//    __weak __typeof(&*self)weakSelf = self;
    [signalrSwift signalROpenWithUrl:signalRString headers:headers hubName:@"" blockfunc:^(NSString * _Nonnull message) {
        
       
        
    }];



结束

这个项目只时候后台是Asp.Net Core 如果后台用别的写的话可以找一下别的框架 项目是有自动重连机制的 。新版本暂时还不知道如何桥接过去OC调用。