Search code examples
swiftsocketsclientnsdata

Get photo from android server to iOS


I want to send image file from android server to iOS client. I'm using swift language and socket programming(ip-port). There is connection. I send/get string data but i can't get image file. How can i get image file on swift side?

i want to make like this app

        if aStream == self.inputStream{
            var buffer: UInt8 = 0
            var len: Int!


            while (inputStream?.hasBytesAvailable != nil){
                len = inputStream?.read(&buffer, maxLength: 2048)

                if len > 0{

                    var output = NSData(bytes: &buffer, length: len)

                    if output != nil{

                        var img = UIImage(data: output) //Error !!!

                    }
                } 
            }
        }

Solution

  • InputStream cannot take all data at once; so you need to append the bytes throughout iteration with an NSMutableData object until hasBytesAvailable property is false. Which means you have no bytes left, you got all the image data you need. The code below is Swift 3.0 by the way.

    var data = NSMutableData()
    
    fileprivate func handleIncomingMessage(_ stream:Stream) {
        if stream === inputStream {
            let bufferSize = 1024
            var buffer = Array<UInt8>(repeating: 0, count: bufferSize))
            while(inputStream.hasBytesAvailable) {
                let bytesRead = inputStream.read(&buffer, maxLength: bufferSize)
                if bytesRead >= 0 {
                    data.append(&buffer, length: bytesRead)
                }else {
                    if bytesRead == -1 {
                        //TODO: Server closed.
                        ITLog.info("Server closed")
                    }
                }
            }
    
            // `NSMutableData` object now has valid image bytes. 
            // Create an UIImage with `data` object.
            let image = UIImage(data: data)
            clearSocketData()
    
        }
    }
    
    fileprivate func clearSocketData() {
        data = NSMutableData()
    }