summaryrefslogtreecommitdiff
path: root/common/foundation_request.mm
blob: 4d6ca9c5fef65320b0140b66dafea23a19327514 (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#import "foundation_request.h"

#include "TargetConditionals.h"
#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#include <atomic>
#endif

#include <memory>
#include <string>
#include <functional>
#include <llmr/platform/request.hpp>
#include <llmr/platform/platform.hpp>
#include <llmr/util/std.hpp>
#include <uv.h>

uv_once_t request_initialize = UV_ONCE_INIT;
NSURLSession *session = nullptr;

#if TARGET_OS_IPHONE
std::atomic<int> active_tasks;
#endif

void request_initialize_cb() {
    NSURLSessionConfiguration *sessionConfig =
        [NSURLSessionConfiguration defaultSessionConfiguration];
    sessionConfig.timeoutIntervalForResource = 30;
    sessionConfig.HTTPMaximumConnectionsPerHost = 8;
    sessionConfig.requestCachePolicy = NSURLRequestUseProtocolCachePolicy;

    session = [NSURLSession sessionWithConfiguration:sessionConfig];

#if TARGET_OS_IPHONE
    active_tasks = 0;
#endif
}

// We're using a child class to make sure ARC is working correctly, as well as to add activity
// indicators on iOS.
class FoundationRequest : public llmr::platform::Request {
public:
    FoundationRequest(const std::string &url,
                      std::function<void(llmr::platform::Response *)> callback,
                      std::shared_ptr<uv::loop> loop)
        : Request(url, callback, loop) {
#if TARGET_OS_IPHONE
        active_tasks++;
        dispatch_async(dispatch_get_main_queue(), ^(void) {
            [[UIApplication sharedApplication]
                setNetworkActivityIndicatorVisible:(active_tasks > 0)];
        });
#endif
    }

    ~FoundationRequest() {
#if TARGET_OS_IPHONE
        active_tasks--;
        dispatch_async(dispatch_get_main_queue(), ^(void) {
            [[UIApplication sharedApplication]
                setNetworkActivityIndicatorVisible:(active_tasks > 0)];
        });
#endif
    }

    NSURLSessionDataTask *task = nullptr;
};

std::shared_ptr<llmr::platform::Request>
llmr::platform::request_http(const std::string &url,
                             std::function<void(Response *)> callback,
                             std::shared_ptr<uv::loop> loop) {
    uv_once(&request_initialize, request_initialize_cb);

    std::shared_ptr<FoundationRequest> req =
        std::make_shared<FoundationRequest>(url, callback, loop);

    // Note that we are creating a new shared_ptr pointer(!) to make sure there is at least one
    // shared_ptr in existence while the NSURLSession is loading our data. We are making sure in the
    // callback that this pointer gets destroyed again.
    std::shared_ptr<Request> *req_ptr = new std::shared_ptr<Request>(req);

    NSURLSessionDataTask *task = [session
                                  dataTaskWithURL:[NSURL URLWithString:@(url.c_str())]
                                  completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if ([error code] == NSURLErrorCancelled) {
            // We intentionally cancelled this request. 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.
            delete req_ptr;

            return;
        }

        if (!error && [response isKindOfClass:[NSHTTPURLResponse class]]) {
            (*req_ptr)->res->code = [(NSHTTPURLResponse *)response statusCode];
            (*req_ptr)->res->body = {(const char *)[data bytes], [data length]};
        } else {
            (*req_ptr)->res->error_message = [[error localizedDescription] UTF8String];
        }

        (*req_ptr)->complete();

        delete req_ptr;
    }];

    req->task = task;

    [task resume];
    return req;
}

void llmr::platform::cancel_request_http(const std::shared_ptr<Request> &req) {
    if (req) {
        [((FoundationRequest *)(req.get()))->task cancel];
    }
}