Skip to content

Instantly share code, notes, and snippets.

@egomez99

egomez99/app.js Secret

Created April 6, 2015 17:01
Show Gist options
  • Save egomez99/2d968326454e0dd8401c to your computer and use it in GitHub Desktop.
Save egomez99/2d968326454e0dd8401c to your computer and use it in GitHub Desktop.
Case 4020: IOS Background Fetch is not working
var url = "http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo";
var win = Ti.UI.createWindow({
backgroundColor : 'white',
layout: 'vertical'
});
var b1 = Ti.UI.createButton({
title : 'Service Start',
top : 50
});
win.add(b1);
b1.addEventListener("click", doIOSBackGroundSessionFetch);
var b2 = Ti.UI.createButton({
title : 'XHR Start',
top : 50
});
win.add(b2);
b2.addEventListener("click", doHttpClientFetch);
win.open();
function doIOSBackGroundSessionFetch() {
var urlSession = require("com.appcelerator.urlSession");
// Create a session configuration
// The string parameter is an arbitrary string used to identify the session in events
var sessionConfig = urlSession.createURLSessionBackgroundConfiguration("com.test.background");
// Create a session
var session = urlSession.createURLSession(sessionConfig);
// Create a background download task to get the data with the URL
urlSession.backgroundDownloadTaskWithURL(session, url);
Ti.App.iOS.addEventListener("downloadcompleted", function(e) {
Ti.API.info('e' + JSON.stringify(e));
alert("<<<download completed>>> " + JSON.stringify(e));
// Invalidate the session and cancel current session tasks
urlSession.invalidateAndCancel(session);
});
Ti.App.iOS.addEventListener('sessioncompleted', function(event) {
Ti.API.info("sessioncompleted " + JSON.stringify(event));
if (event.success) {
Ti.API.info("Downloads completed successfully.");
}
Ti.API.info("Download task :" + event.taskIdentifier + " completed, success ? : " + event.success);
});
}
function doHttpClientFetch() {
var xhr = Ti.Network.createHTTPClient({
onload : function() {
Ti.API.debug(this.responseText);
alert(JSON.parse(this.responseText));
},
onerror : function(e) {
Ti.API.debug("STATUS: " + this.status);
Ti.API.debug("TEXT: " + this.responseText);
Ti.API.debug("ERROR: " + e.error);
alert('There was an error retrieving the remote data. Try again.');
},
timeout : 5000
});
xhr.open("GET", url);
xhr.send();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment