Swift初心者です。Socket通信を利用してサーバーとクライアントでデータを送り合うということしたいと思っています。
リンク内容
<SwiftでWebSocket通信のテスト>
上記のサイトを参考にローカルでのSocket通信を試みようとしたのですが、以下の不具合が生じます。
・tableViewに日時が表示されない
・ボタンを押すとThread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional valueエラーが出てアプリが停止する
サーバー側のNode.jsはサイトのをそのまま利用し問題なく動いている状態です。
Socket通信のやりとりにおいて問題があると思い色々調べてみましたが上記の問題は解決しませんでした。
どうかアドバイスをお願いいたします。
Swift
1<ViewController.Swift> 2 3import UIKit 4import SocketIO 5 6class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 7 8 @IBOutlet weak var tableView: UITableView! 9 //let SocketURL = NSURL(string:"http://localhost:8080/") 10 var dataList:NSMutableArray! 11 var socket: SocketIOClient! 12 13 override func viewDidLoad() { 14 super.viewDidLoad() 15 // Do any additional setup after loading the view, typically from a nib. 16 tableView.delegate = self 17 tableView.dataSource = self 18 19 dataList = NSMutableArray() 20 21 22 let manager = SocketManager(socketURL: URL(string: "http://localhost:8080")!, config: [.log(true), .compress]) 23 let socket = manager.defaultSocket 24 //socket = SocketIOClient(manager: SocketURL! as! SocketManagerSpec, nsp:[.Log(true), .ForcePolling(true)]) *この記述はエラーになる 25 socket.on(clientEvent: .connect) { data, ack in 26 print("socket connected!!") 27 } 28 socket.on(clientEvent: .disconnect) { data, ack in 29 print("socket disconnected!!") 30 } 31 32 socket.on("from_server") { data, emitter in 33 if let message = data as? [String] { 34 print(message[0]) 35 self.dataList.insert(message[0], at:0) 36 self.tableView.reloadData() 37 } 38 } 39 socket.connect() 40 } 41 42 override func didReceiveMemoryWarning() { 43 super.didReceiveMemoryWarning() 44 // Dispose of any resources that can be recreated. 45 } 46 ////////////tableView関連/////////////////// 47 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 48 return dataList.count 49 } 50 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 51 return 52 } 53 func numberOfSections(in tableView: UITableView) -> Int { 54 return 1 55 } 56 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 57 return 50 58 } 59 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 60 let cell : UITableViewCell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell") 61 cell.textLabel?.text = dataList[indexPath.row] as? String 62 return cell 63 } 64 65 @IBAction func clickButton(_ sender: Any) { 66 socket.emit("from_client", "button pushed!!") 67 68 } 69 70} 71
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/12/15 12:57
2017/12/18 02:43
2017/12/18 05:17