Gomobile 绑定(bind)委托(delegate)/回调行为

标签 go callback gomobile

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

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

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

最佳答案

事实证明这是可能的!

这是 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];
}

关于Gomobile 绑定(bind)委托(delegate)/回调行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41856287/

相关文章:

go - 存储 Go 编码数据的通用函数

Go Coverage 不包括其他包中的函数

javascript - 调用 JavaScript 回调

.net-3.5 - WCF 回调 channel 被过早处置?

java - 找不到 "libgojni.so"

api - 如何在 Go 中向 API 文档添加示例?

postgresql - Golang 在搜索 Postgres 时崩溃

c++ - 是否可以将 C 风格的 api 回调/处理程序适应 C++ 以进行类相关的动态创建?

戈兰 : Gomobile app cannot generate files

gomobile:iOS 上的错误返回值同时具有 NSError 和 bool 返回值