Swift 3 ViewDidLoad和NSStream;

时间:2016-11-28 22:45:00

标签: ios sockets tcp nsstream

可以在ViewDidLoad中创建套接字吗?我在这里创建了一个NSStream套接字,打开它,写入它,关闭它并挂起

我需要通过UI交互发送数据;我怎么能这样做?

这是异步还是同步问题?

请看帖子:

Porting code to UIViewController not working

我在没有iOS生命周期的情况下工作,它可以工作,但是一旦我将它移植到我的iOS应用程序,即UIViewController

,它就无法工作

最新更新:

import Darwin
import Foundation
import UIKit
import Dispatch

class ViewController: UIViewController {

    @IBOutlet private weak var joystickMove: Joystick!
    @IBOutlet private weak var joystickRotate: Joystick!

    private var contour = Contours()
    private var contour_index: Int = 0
    private var port: UInt32 = 7014


    //    var socket = Connection(address: "000.000.0.000" as String, port: 0000)
    //    socket.connect()


    override func viewDidLoad() {
        super.viewDidLoad()
        createJoystick()
        createContours()
        createButton()
    }

    private func createJoystick() {

        var joystick = Joystick()

        let n: CGFloat = 100.0
        let x: CGFloat = (UIScreen.main.bounds.width/2) - (n/2.0)
        let y: CGFloat = UIScreen.main.bounds.height - (UIScreen.main.bounds.height/4.0)

        joystick.frame = CGRect(x: x, y: y, width: n, height: n)
        joystick.backgroundColor =  UIColor.clear

        joystick.substrateColor = UIColor.lightGray
        joystick.substrateBorderColor = UIColor.gray
        joystick.substrateBorderWidth = 1.0
        joystick.stickSize = CGSize(width: 50.0, height: 50.0)
        joystick.stickColor = UIColor.darkGray
        joystick.stickBorderColor = UIColor.black
        joystick.stickBorderWidth = 2.0
        joystick.fade = 0.5

        var packet = ""

        joystick.trackingHandler = { (data) -> () in

            let power = sqrt(pow(Double(data.velocity.x), 2.0) + pow(Double(data.velocity.y), 2.0))
            let theta = atan2(Double(-data.velocity.y), Double(data.velocity.x))
            let degrees = theta * (180.0 / M_PI)

            if degrees >= 55 && degrees <= 125 { // move forward
                packet = "\(1) \(1) \(power) \(power)"
            } else if degrees >= -125 && degrees <= -55 { // move backewards
                packet = "\(-1) \(-1) \(power) \(power)"
            } else if degrees >= -55 && degrees <= 55 { // turn right
                packet = "\(1) \(-1) \(power) \(power)"
            } else if (degrees >= 125 && degrees <= 180) && (degrees >= -180 && degrees <= -125) { // turn left
                packet = "\(-1) \(1) \(power) \(power)"
            }

        }

        print("packet: \(packet)")



        DispatchQueue.global(qos: .userInitiated).async { // do some task
            var socket = Connection(address: "000.000.00.000" as String, port: 0000)
            socket.connect()

            let sent = socket.sendMessage(message: packet)

            if sent {

                print("packet was sent!")

            }

            socket.disconnect()
        }

        //        DispatchQueue.global(qos: .background).async { // do some task
        //            let sent = socket.sendMessage(message: "Hey you!")
        //        }

        view.addSubview(joystick)
    }

    private func createContours() {
        let n: CGFloat = 350.0
        let x: CGFloat = (UIScreen.main.bounds.width/2.0) - (n/2.0)
        let y: CGFloat = UIScreen.main.bounds.height - (UIScreen.main.bounds.height/4.0) - n - 100.0
        self.contour.frame = CGRect(x: x, y: y, width: n, height: n)
        self.contour.backgroundColor = UIColor.clear
        view.addSubview(self.contour)
    }

    private func createButton() {
        let width: CGFloat = 150.0
        let height: CGFloat = 75.0
        let x: CGFloat = (UIScreen.main.bounds.width/2.0) - (width/2.0)
        let y: CGFloat = UIScreen.main.bounds.height - (UIScreen.main.bounds.height/4.0) - width

        let button: UIButton = UIButton(frame: CGRect(x: x, y: y, width: width, height: height))
        button.backgroundColor = UIColor.blue
        button.setTitle("Contour Views", for: .normal)
        button.addTarget(self, action: #selector(self.buttonAction), for: .touchUpInside)
        button.tag = 1
        view.addSubview(button)
    }

    @objc private func buttonAction(sender: UIButton!) {
        var btnsendtag: UIButton = sender
        if btnsendtag.tag == 1 {
            self.contour_index = (self.contour_index + 1) % 2
            switch self.contour_index {
            case 0:
                for index in 0...356 {
                    if self.contour.distx[index] != -1 && self.contour.disty[index] != -1 {
                        self.contour.circles[index].alpha = 0
                    }
                }
            case 1:
                for index in 0...356 {
                    if self.contour.distx[index] != -1 && self.contour.disty[index] != -1 {
                        self.contour.circles[index].alpha = 1
                    }
                }
            default:
                for index in 0...356 {
                    if self.contour.distx[index] != -1 && self.contour.disty[index] != -1 {
                        self.contour.circles[index].alpha = 1
                        UIColor.cyan.setFill()
                        self.contour.lines[index].fill()
                        self.contour.lines[index].stroke()
                    }
                }
            }

        }
    }

    public func perform(socket: Connection, completion:@escaping (Bool) -> ()) {
        let sent = socket.sendMessage(message: "Hey you!")
        if sent {
            completion(true)
        } else {
            completion(false)
        }
    }

    override func viewDidAppear(_ animated: Bool) {


        DispatchQueue.global(qos: .background).async { // do some task
            var socket = Connection(address: "192.168.43.217" as String, port: 7014)
            socket.connect()

            let sent = socket.sendMessage(message: "hello")

            if sent {

                print("packet was sent!")

            }

            socket.disconnect()
        }

    }

    //    delayWithSeconds(1) {
    //    //Do something
    //    }

    public func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) {
        DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
            completion()
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

0 个答案:

没有答案