引言
此代码是写完公司项目后整理的并没有测试,仅仅提供思路
读取p12证书请添加到Data扩展
func identity(password: String) throws -> SecIdentity {
var importResult: CFArray? = nil
let err = SecPKCS12Import(
self as NSData,
[kSecImportExportPassphrase as String: password] as NSDictionary,
&importResult
)
guard err == errSecSuccess else {
throw NSError(domain: NSOSStatusErrorDomain, code: Int(err), userInfo: nil)
}
let identityDictionaries = importResult as! [[String:Any]]
return identityDictionaries[0][kSecImportItemIdentity as String] as! SecIdentity
}
定义连接context
var conn: NWConnection!
在扩展里面加入代码连接TLS
func connectedToHost(ip:String,port:UInt16,queue:String,localCert:String?,pass:String?) -> Bool {
let queue = DispatchQueue(label:queue)
let host = NWEndpoint.Host(ip)
let port = NWEndpoint.Port(integerLiteral: port)
//Create TLS Configureation
let options = NWProtocolTLS.Options()
//Set Local Cert
if localCert != nil && pass != nil {
let data = try? Data(contentsOf: URL(string: localCert!)!)
let certArray:SecIdentity? = try?data?.identity(password: "12345678")
if certArray != nil{
sec_protocol_options_set_local_identity(options.securityProtocolOptions,sec_identity_create(certArray!)!)
}else{
delegate?.didDisConnect(err: "Load Local Cert Fail")
}
}
//Set Very Cert
//always trust
sec_protocol_options_set_verify_block(options.securityProtocolOptions, {
(sec_protocol_metadata, sec_trust, sec_protocol_verify_complete) in
sec_protocol_verify_complete(true)
}, queue)
//create Connection
conn = NWConnection(host: host, port: port, using: NWParameters(tls: options))
//start
conn.start(queue: queue)
return true
}
数据读写
//send data
func send(data:Data,tag:Int16){
conn.send(content: data, completion: .contentProcessed({ (error) in
if let error = error {
//Data Send Error
print(error)
self.conn.cancel()
} else {
//Data send Success
print("send Success")
}
guard delegate != nil else{return}
delegate?.didWriteData(err: error, tag: tag)
}))
}
//rev data
func receive(length:Int,tag:Int16){
conn.receive(minimumIncompleteLength: length, maximumLength: length) { (data, context, isComplete, error) in
if let error = error {
print(error)
//具体实现需要判断错误再断开
self.conn.cancel()
return
}
if let data = data {
print("receive:\(data)")
}
if isComplete {
self.conn.cancel()
}
}
}
//close connect
func cannel(){
conn.cancel()
}