Gomobile 绑定委托/回调行为



>有人知道是否可以使用 gomobile 绑定在导出到 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];
}

最新更新