Ejecta
Ejecta copied to clipboard
How to download file to Document folder
like title says. thanks
I try to implement it , @phoboslab , Could you offer me some advices ? Thanks. ( it has passed base test)
- (void) download:(NSString *)urlStr destination:(NSString *)destination callback:(JSObjectRef)callback {
NSString *filePath = [scriptView pathForResource:destination];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSString *errorDesc = NULL;
if (error) {
NSLog(@"Download Error:%@",error.description);
}
if (data) {
[data writeToFile:filePath atomically:YES];
NSLog(@"File is saved to %@",filePath);
}
if( callback ) {
JSContextRef gctx = scriptView.jsGlobalContext;
JSStringRef jsFilePath = JSStringCreateWithUTF8CString([filePath UTF8String]);
JSStringRef jsErrorDesc = errorDesc?JSStringCreateWithUTF8CString([errorDesc UTF8String]):NULL;
JSValueRef params[] = {
error?JSValueMakeString(gctx, jsErrorDesc):JSValueMakeNull(gctx),
JSValueMakeString(gctx, jsFilePath)
};
[scriptView invokeCallback:callback thisObject:NULL argc:2 argv:params];
JSValueUnprotectSafe(gctx, callback);
}
}];
}
EJ_BIND_FUNCTION(download, ctx, argc, argv)
{
NSString *url = JSValueToNSString(ctx, argv[0]);
NSString *destination = JSValueToNSString(ctx, argv[1]);
JSObjectRef callback = nil;
if (argc == 3){
callback = JSValueToObject(ctx, argv[2], NULL);
if (callback) {
JSValueProtect(ctx, callback);
}
}
[self download:url destination:destination callback:callback];
return JSValueMakeBoolean(ctx, true);
}
use case AppUtils is my Extension
var appUtils = new Ejecta.AppUtils();
appUtils.download("http://www.foo.com/bar.file","${Documents}/bar.file", function(err, filePath){
console.log("err",err);
console.log("filePath",filePath);
});