Gomobile绑定委托/回调行为

Gomobile绑定委托/回调行为,go,callback,gomobile,Go,Callback,Gomobile,有人知道在导出到iOS时,是否可以使用gomobile绑定实现某种委托行为吗 i、 我有一个go库,可以处理iOS应用程序的网络请求,我需要异步完成,这样它就不会挂起应用程序 解决方案是要么发送一个objc完成块(我认为这不起作用,因为我没有办法将objc代码发送回go函数),要么实现某种委托,这样应用程序就可以知道请求何时完成。我已经尝试了我能想到的一切。。。有什么想法吗?谢谢 结果证明这是可能的 以下是Go代码: type NetworkingClient struct {} func C

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

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


解决方案是要么发送一个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))
        }()
  }
在Objective-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];
}

事实证明这是可能的

以下是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))
        }()
  }
在Objective-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];
}