Skip to content

Instantly share code, notes, and snippets.

@mathieugarcia
Created May 14, 2018 13:13
Show Gist options
  • Save mathieugarcia/3dad5f05c247dd3be1c4a2ded7e3c36b to your computer and use it in GitHub Desktop.
Save mathieugarcia/3dad5f05c247dd3be1c4a2ded7e3c36b to your computer and use it in GitHub Desktop.
The HTTP Request class/wrapper
template <typename DoneLambda, typename ErrorLambda>
class HTTPRequest
{
public:
HTTPRequest(const std::string& rURL,
DoneLambda&& rDone,
ErrorLambda&& rError)
: mURL(rURL),
mDone(std::forward<DoneLambda>(rDone)),
mError(std::forward<ErrorLambda>(rError))
{
}
auto operator()() noexcept -> void
{
auto url = [NSURL URLWithString:
[NSString stringWithUTF8String:mURL.c_str()]];
auto session = [NSURLSession sharedSession];
// Copy attributes for this block.
__block auto done_lambda = mDone;
__block auto error_lambda = mError;
auto task = [session dataTaskWithURL:url
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error)
{
auto httpResponse = (NSHTTPURLResponse *) response;
// Error!
if (error != nil || httpResponse == nil ||
httpResponse.statusCode != 200 || data == nil)
{
// Force-dispatch on main thread
dispatch_async(dispatch_get_main_queue(),
^{
error_lambda([[error localizedDescription] UTF8String]);
});
}
else // Success! Pass the buffer and length to the lambda
{
__block const auto len = data.length;
__block auto buf = std::unique_ptr<char[]>(new char[len]);
memcpy(buf.get(), data.bytes, len);
dispatch_async(dispatch_get_main_queue(),
^{
done_lambda(std::move(buf), len);
});
}
}
}];
[task resume];
}
private:
const std::string mURL;
DoneLambda mDone;
ErrorLambda mError;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment