Skip to content

Instantly share code, notes, and snippets.

@Gandum2077
Created January 8, 2020 02:21
Show Gist options
  • Select an option

  • Save Gandum2077/96013bd20d0ae6b7e5d1c48af66750f9 to your computer and use it in GitHub Desktop.

Select an option

Save Gandum2077/96013bd20d0ae6b7e5d1c48af66750f9 to your computer and use it in GitHub Desktop.
Download files with shared session
function download(params) {
params = params || {};
params.handlers = params.handlers || {};
const url = params.url;
const method = params.method || "GET";
const timeout = params.timeout || 60;
const header = params.header || {};
const body = params.body;
const callback = params.handler;
const request = $objc("NSMutableURLRequest").$requestWithURL($objc("NSURL").$URLWithString(url));
request.$setHTTPMethod(method);
request.$setTimeoutInterval(timeout);
for (const [key, value] of Object.entries(header)) {
request.$addValue_forHTTPHeaderField(value, key);
}
if (body) {
request.$setHTTPBody(body.ocValue());
}
const session = $objc("NSURLSession").$sharedSession();
const completionHandler = $block("void, NSURL *, NSURLResponse *, NSError *", (location, response, error) => {
if (callback) {
const data = $objc("NSData").$dataWithContentsOfURL(location).$copy();
$thread.main({
handler: () => {
callback({
"data": data.jsValue(),
"response": response.jsValue(),
"error": error.jsValue(),
});
}
});
}
});
const task = session.$downloadTaskWithRequest_completionHandler(request, completionHandler);
task.$resume();
}
// exports.download = download;
download({
"url": "https://www.apple.com/v/iphone/home/z/images/overview/the_ultimate_iphone_large_2x.jpg",
"method": "GET", // Optional, default to GET
"timeout": 60, // Optional, default to 60
"header": {}, // Optional, default to {}
"body": null, // Optional, default to null
"handler": result => {
console.log(`Finished: ${JSON.stringify(result)}`);
// props: data, response, error
const data = result.data;
if (data) {
$share.sheet(data);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment