itZme itZme - 1 month ago 21
Swift Question

Reading stdio from Mac Application

I am working on a Mac OSX application, that can act as a Chrome Native Messaging host application. As per Native Message API standards, the messages can only be shared between the Chrome Extension and the Mac app, through Standard IO (stdin, stdout).

I have tried implementing this with readLine() function, available from Swift 3.0 and also tried the classic way with FileHandle.

But these implementations causing some weird issues in main thread.

Can anybody please suggest any solution or reference links?

Answer

NSFileHandle, a wrapper for file descriptor is the solution.You can use file handle objects to access data associated with files, sockets, pipes, and devices. For files, you can read, write, and seek within the file.

DispatchQueue.global(qos: .background).async {
        let input = FileHandle.standardInput
        var aStr : String!
        while true {
            //Read first 4 bytes to get message length details(As per NativeMessagingAPI protocol)
            let lengthDetails = input.readData(ofLength:4)
            let length = lengthDetails.withUnsafeBytes { (ptr: UnsafePointer<Int32>) -> Int32 in
                return ptr.pointee
            }
            let data = input.readData(ofLength:Int(length))//input.availableData
            if (data.count > 0) {
                var aStr = String(data:data, encoding:String.Encoding.utf8)
                if (aStr != nil) {
                    DispatchQueue.main.async {
                        //Handle data logic here
                    }
                }
            }
        }

    }