UI hangs when Go code called from Swift communicates over the network; time.Sleep works fine

32 Views Asked by At

I used quic-go to implement a function to send messages to the server and receive data, which I turned into an iOS library with the gomobile bind command.

func Fetch(message string) ([]byte) {
    fmt.Printf("Client: Sending '%s'\n", message)
    
    stream, err := conn.OpenStreamSync(context.Background())  // conn is of type quic.Connection.
    if err != nil {
        fmt.Printf("go_Client: Error opening stream: %s\n", err)
    }

    fmt.Printf("go_client: Sending '%s'\n", message)
    _, err = stream.Write([]byte(message))
    if err != nil {
        fmt.Printf("go_client: Error writing to stream: %s\n", err)
    }

    bufferSize := 1024
    var receivedData []byte 

    for {
        buf := make([]byte, bufferSize)
        n, err := stream.Read(buf)
        if err != nil {
            if err == io.EOF {
                break 
            }
            fmt.Printf("Client: Error reading from stream: %s\n", err)
            break
        }
        receivedData = append(receivedData, buf[:n]...) 
    }
    
    stream.Close()

    return receivedData
}

This function is called in swift as follows.

func fetchObjectFromServer(_ message: String, completion: @escaping (Data?) -> Void) {
    Task.detached{
        let data = QuicFetch(message)
        if let unwrappedData = data {
            completion(unwrappedData)
        } else {
            completion(nil)
        }
    }
}

I am using "Task.detached" to make asynchronous calls, but when the QuicFetch function starts processing, the UI stops.

I experimentally modified the code of golang's Fetch function as follows and used it in the same way in swift.

func Fetch() {
    sleepTime := 10 * time.Second
    fmt.Printf("start sleep\n")
    time.Sleep(sleepTime)
    fmt.Printf("end sleep\n")
}

This function was properly processed in the background and the UI did not stop.

I would like to know why the UI stops when trying to process in the background only when communicating with quic-go.

I have questioned other communities but have not gotten satisfactory remedies.

0

There are 0 best solutions below