blob: d7ab26cefadfc7ddabbaa73e960569a766d31bdc (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
#import <Foundation/Foundation.h>
#include <memory>
#include <string>
#include <functional>
#include <llmr/platform/platform.hpp>
namespace llmr {
class platform::Request {
public:
Request(NSURLSessionDataTask *task, const std::string &original_url)
: task(task), original_url(original_url) {}
NSURLSessionDataTask *task;
std::string original_url;
};
std::shared_ptr<platform::Request>
platform::request_http(const std::string &url, std::function<void(Response *)> background_function,
std::function<void()> foreground_callback) {
__block std::shared_ptr<Request> req;
NSURLSessionDataTask *task = [[NSURLSession sharedSession]
dataTaskWithURL:[NSURL URLWithString:@(url.c_str())]
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// Make sure we clear the shared_ptr to resolve the circular reference. We're referencing
// this shared_ptr by value so that the object stays around until this completion handler is
// invoked.
req.reset();
if ([error code] == NSURLErrorCancelled) {
// We intentionally cancelled this request. Do nothing.
return;
}
Response res;
if (!error && [response isKindOfClass:[NSHTTPURLResponse class]]) {
res.code = [(NSHTTPURLResponse *)response statusCode];
res.body = {(const char *)[data bytes], [data length]};
} else {
res.code = -1;
res.error_message = [[error localizedDescription] UTF8String];
}
background_function(&res);
dispatch_async(dispatch_get_main_queue(), ^(void) {
foreground_callback();
});
}];
req = std::make_shared<Request>(task, url);
[task resume];
return req;
}
void platform::cancel_request_http(const std::shared_ptr<Request> &req) {
if (req) {
[req->task cancel];
}
}
}
|