Gomobile 绑定 delegate/callback 行为

Gomobile bind delegate/callback behaviour

有人知道是否可以使用 gomobile bind 在导出到 iOS 时实现某种委托行为吗?

即我有一个处理 iOS 应用程序网络请求的 go 库,我需要它异步完成,这样它就不会挂起应用程序。

解决方案是发送一个 objc 完成块(我认为这行不通,因为我没有找到将 objc 代码发送回 go 函数的方法)或实现某种委托,以便应用程序可以知道请求何时完成。我已经尝试了所有我能想到的……有什么想法吗?谢谢!

事实证明这是可能的!

这是 Go 代码:

type NetworkingClient struct {}

func CreateNetworkingClient() *NetworkingClient {
    return &NetworkingClient {}
}

type Callback interface {
    SendResult(json string)
}

func (client NetworkingClient) RequestJson (countryCode string, callback Callback) {
    go func () {
    safeCountryCode := url.QueryEscape(countryCode)
    url := fmt.Sprintf("someApi/%s", safeCountryCode)

    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        //Handle error
    }

    httpClient := &http.Client{}

    resp, err := httpClient.Do(req)
    if err != nil {
        //Handle error
    }

    defer resp.Body.Close()
      b, err := ioutil.ReadAll(resp.Body)
      callback.SendResult(string(b))
        }()
  }

在Objetive-C中实现如下:

- (void)start {

    ...

    EndpointNetworkingClient* client = EndpointCreateNetworkingClient();
    [client requestJson:countryCode callback:self];
}

//Receives the json string from Go.
- (void)sendResult:(NSString*)json{
    NSData *data = [json dataUsingEncoding:NSUTF8StringEncoding];
    id jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    [self handleResponse:jsonDictionary];
}