|
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); |
|
} |
|
} |
|
}); |