Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[TIMOB-17502] iOS: URLSession DownloadCompleted event now returns file url instead of TiBlob #6527

Merged
merged 5 commits into from Jan 7, 2015

Conversation

cheekiatng
Copy link
Contributor

JIRA: https://jira.appcelerator.org/browse/TIMOB-17502

To test:

// Require in the urlSession module
var urlSession = require("com.appcelerator.urlSession");
var session;

// App UI
var win = Ti.UI.createWindow({backgroundColor:"white"});
var progress = Ti.UI.createProgressBar({
    width: 200,
    height: 50,
    min: 0,
    max: 1,
    value: 0,
    style: Ti.UI.iPhone.ProgressBarStyle.PLAIN,
    top: 10,
    message: 'Downloading image URL',
    font: { fontSize: 12, fontWeight: 'bold'},
    color: '#888'
});
win.add(progress);
var imageView = Ti.UI.createImageView({
        top:150,
          height:300,
          width:200
    });
win.add(imageView);

var button = Ti.UI.createButton({
    title:'Download Image (url)',
    height:40,
    width:200,
    top:70
});

button.addEventListener('click', function()
{
    // Check if the device is running iOS 8 or later, before registering for local notifications
    if (Ti.Platform.name == "iPhone OS" && parseInt(Ti.Platform.version.split(".")[0]) >= 8) {
        Ti.App.iOS.registerUserNotificationSettings({
           types: [
                Ti.App.iOS.USER_NOTIFICATION_TYPE_ALERT,
                Ti.App.iOS.USER_NOTIFICATION_TYPE_SOUND,
                Ti.App.iOS.USER_NOTIFICATION_TYPE_BADGE
            ]
        });
    }
    // Create a session configuration
    // The string parameter is an arbitrary string used to identify the session in events
    var sessionConfig = urlSession.createURLSessionBackgroundConfiguration("com.appcelerator.test");
    // Create a session
    session = urlSession.createURLSession(sessionConfig);
    // Create a background download task to get the asset with the URL
    //urlSession.backgroundDownloadTaskWithURL(session,"https://raw.github.com/appcelerator-developer-relations/KitchenSink/master/Resources/images/dog@2x~iphone.jpg"); //small file
    //urlSession.backgroundDownloadTaskWithURL(session,"http://imgsrc.hubblesite.org/hu/db/images/hs-2004-07-a-full_jpg.jpg"); //medium sized file
    urlSession.backgroundDownloadTaskWithURL(session,"http://www.wswd.net/testdownloadfiles/1GB.zip"); //huge file
    progress.show();
});

win.add(button);
win.open();

// Monitor this event to receive updates on the progress of the download
Ti.App.iOS.addEventListener("downloadprogress", function(e) {
    // Update the progress indicator
    progress.value = (e.totalBytesWritten/e.totalBytesExpectedToWrite);
});


// Monitor this event to know when the download completes
Ti.App.iOS.addEventListener("downloadcompleted", function(e) {
    Ti.API.info("download completed " + JSON.stringify(e));
    var cacheFile = e.data.getFile();
    var downloadedFile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, cacheFile.getName());
    downloadedFile.write(e.data); // copy and save from cache
    Ti.API.info("downloadedFile: " + downloadedFile.getNativePath());
    // set new Image
    //imageView.image = e.data;
    // Invalidate the session and cancel current session tasks
    urlSession.invalidateAndCancel(session);

    // Notify the user the download is complete if the application is in the background
    var notification = Ti.App.iOS.scheduleLocalNotification({
        alertBody: "Download completed!",
        badge: 1,
        sound: "/alert.wav",
        date: new Date(new Date().getTime())
    });

    progress.hide();
});


// Monitor this event to know when all session tasks have completed
Ti.App.iOS.addEventListener('sessioncompleted', function(e) {
    Ti.API.info("sessioncompleted " + JSON.stringify(e));
    if (e.success) {
        alert("Downloads completed successfully.");
    }
});
  • Create a new Project
  • Double-click the Project's "tiapp.xml" file to open it in the Overview tab.
  • In the Modules section, click the Add button (green plus sign) to open the Mobile Modules dialog.
  • Locate and select "com.appcelerator.urlSession".
  • Click OK.
  • Copy the code segment above to the project "app.js" file
  • Run the Project
  • Note: the link downloaded is 1GB in size in the test code above. Replace with commented out lines of code linked to smaller files if necessary.

if (!success) {
DebugLog(@"Unable to copy temp file. Error: %@", [error localizedDescription]);
}
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithUnsignedInteger:downloadTask.taskIdentifier ],@"taskIdentifier",destinationURL,@"url", nil];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would not change the event parameters at all. You could always create a TiBlob with a file path
TiBlob* data = [[[TiBlob alloc] initWithFile:[destinationURL path]] autorelease];

That way the signature remains the same and the data is still in a file

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! that works and event parameters can stay the same.

@vishalduggal
Copy link
Contributor

Code Reviewed. Please address comments

//copy downloaded file from location to tempFile (in NSTemporaryDirectory), because file in location will be removed after delegate completes
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *destinationFilename = downloadTask.originalRequest.URL.lastPathComponent;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is going to be a problem. What if the original URL in the request has no path component
http://www.myfileserved.com/.

You could instead use the URL provided by the location parameter

@vishalduggal
Copy link
Contributor

Code reviewed. Please address comments

@jonalter
Copy link
Contributor

jonalter commented Jan 7, 2015

FT pass

jonalter added a commit that referenced this pull request Jan 7, 2015
[TIMOB-17502] iOS: URLSession DownloadCompleted event now returns file url instead of TiBlob
@jonalter jonalter merged commit 01d6e76 into tidev:master Jan 7, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants