0
- (IBAction)newSearchToolBarButtonAction:(id)sender
{
    NSLog(@"New Search");
    CURL *curl;
    CURLcode res;

    curl = curl_easy_init();
    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "https://www.google.com/");
        res = curl_easy_perform(curl);

        /* always cleanup */
        curl_easy_cleanup(curl);
    }

}

这是我当前的代码。它通过在控制台中显示结果来工作,但我想把它放到一个 NSString 中。我该怎么做呢?

4

1 回答 1

0

经过一番折腾并查看其他示例代码后,我找到了一个可行的解决方案。我不确定这是最好的方法......但它确实有效。

- (IBAction)newSearchToolBarButtonAction:(id)sender
{
    NSLog(@"New Search");
    CURL *curl;
    CURLcode res;
    char *msg_in = calloc(1,sizeof(char));

    curl = curl_easy_init();
    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "http://www.google.com");
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &msg_in);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, http_get_response);

        res = curl_easy_perform(curl);

        NSLog(@"cURL-Res=%u",res);

        //NSLog(@"Buffer=%s",msg_in);

        NSString *string = [NSString stringWithCString:msg_in encoding:NSUTF8StringEncoding];
        NSLog(@"String=%@",string);

        /* always cleanup */
        curl_easy_cleanup(curl);
    }

}

int http_get_response(void *buffer, size_t size, size_t rxed, char **msg_in)
{
    char *c;

    if (asprintf(&c, "%s%.*s", *msg_in, size * rxed, buffer) == -1) {
        free(*msg_in);
        msg_in = NULL;
        return -1;
    }

    free(*msg_in);
    *msg_in = c;

    return size * rxed;
}
于 2013-08-06T13:28:22.700 回答