a. Implement the HTTP Client object
b. Retrieve data in various formats from network services
c. Upload and download files across the network
d. Post JSON-formatted data to a web service; receive and process JSON data from a network endpoint
e. Receive and process XML data from a network endpoint
f. Handle network and data errors
Exercise - 1
Implement the HTTP Client object and analyse XML HTTP Request Life Cycle
Implement the HTTP Client object and analyse XML HTTP Request Life Cycle
Solution
Retrieve data in various formats from network services
function xhrlifecycle(){
var xhr = Ti.Network.createHTTPClient({
onload: function(e) {
// function called in readyState DONE (4)
Ti.API.info('onload called, readyState = '+this.readyState);
},
onerror: function(e) {
// function called in readyState DONE (4)
Ti.API.info('onerror called, readyState = '+this.readyState);
},
ondatastream: function(e) {
// function called as data is downloaded
Ti.API.info('ondatastream called, readyState = '+this.readyState);
},
onsendstream: function(e) {
// function called as data is uploaded
Ti.API.info('onsendstream called, readyState = '+this.readyState);
},
onreadystatechange: function(e) {
switch(this.readyState) {
case 0:
// after HTTPClient declared, prior to open()
// though Ti won't actually report on this readyState
Ti.API.info('case 0, readyState = '+this.readyState);
break;
case 1:
// open() has been called, now is the time to set headers
Ti.API.info('case 1, readyState = '+this.readyState);
break;
case 2:
// headers received, xhr.status should be available now
Ti.API.info('case 2, readyState = '+this.readyState);
break;
case 3:
// data is being received, onsendstream/ondatastream being called now
Ti.API.info('case 3, readyState = '+this.readyState);
break;
case 4:
// done, onload or onerror should be called now
Ti.API.info('case 4, readyState = '+this.readyState);
break;
}
},
timeout:5000 /* in milliseconds */
});
xhr.open("GET", 'http://api.sba.gov/rec_sites/keywords/domain/irs.json');
xhr.send(); // request is actually sent with this statement
}
Exercise - 2
Retrieve data in various formats from network services
Solution
download files across the network
Detect Network Change
function httpnetwork(){
var url = "http://api.sba.gov/rec_sites/keywords/domain/irs.xml";
var xhr = Ti.Network.createHTTPClient({
onload: function(e) {
// this function is called when data is returned from the server and available for use
// this.responseData holds any returned binary data
Ti.API.info(this.responseXML); // this.responseXML holds any returned XML (including SOAP)
},
onerror: function(e) {
// this function is called when an error occurs, including a timeout
Ti.API.info('Error from network');
Ti.API.info(e.error);
//alert('error');
},
timeout:5000 /* in milliseconds */
});
xhr.open("GET", url);
xhr.send(); // request is actually sent with this statement
}
Exercise - 3
download files across the network
Solution
function downloadfile(){
var file ;
var xhr = Titanium.Network.createHTTPClient({
onload: function() {
// first, grab a "handle" to the file where you'll store the downloaded data
file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'myaudio.mp3');
file.write(this.responseData); // write to the file
Ti.App.fireEvent('audio_downloaded', {filepath:file.nativePath});
},
timeout: 10000
});
xhr.open('GET','http://www.freesound.org/data/previews/2/2686_5150-lq.mp3');
xhr.send();
Ti.App.addEventListener('audio_downloaded', function(e) {
//image.image = e.filepath;
Ti.API.info(file.nativePath);
var audio = Titanium.Media.createSound({
url:file.nativePath,
preload: true
});
audio.play();
});
};
Exercise - 4
Post JSON data from a network endpoint
Solution
Receive and process JSON data from a network endpoint
function postJSONData(){
var xhr = Ti.Network.createHTTPClient({
onload: function onLoad() {
alert("Loaded: " + this.status + ": " + this.responseText);
},
onerror: function onError() {
alert("Errored: " + this.status + ": " + this.responseText);
}
});
xhr.open("POST","https://c0ceb560ef3c83761ce4c21a93b2ce718311fa76.cloudapp-enterprise.appcelerator.com/api/newtest");
var authstr = 'Basic ' + Ti.Utils.base64encode('WqrIxir6bD9oHoV07seH4T8vrrnc0rQA:');
xhr.setRequestHeader("Authorization", authstr);
xhr.setRequestHeader("Content-Type","application/json");
xhr.send(JSON.stringify({
"first_name": "Mohan",
"last_name": "Singh",
}));
}
Exercise - 5
Receive and process JSON data from a network endpoint
Solution
var funcToExecute=function () { //function called when GET URL is loaded from HTTP
console.log("inside first cal back");
if(this.status == '200'){
if(this.readyState == 4)
JSONObj=JSON.parse(this.responseText);
var data = [];
for (var i = 0; i < JSONObj.length ; i++) { //Loop through
//for (var i = 0; i < 10 ; i++) {
var listItem = JSONObj[i];
data.push({
title :listItem["name"]
});
}
//Create table and set values
var table = Titanium.UI.createTableView({});
table.setData(data);
$.tableContainer.add(table);
console.log("Table Set");
}
};
//HTTP request call
var xhr=Titanium.Network.createHTTPClient();
xhr.onerror = function(e){
Ti.API.error('Bad Sever =>'+e.error);
};
xhr.open("GET","http://api.sba.gov/geodata/all_links_for_county_of/orange county/ca.json");//ADD your URL
xhr.onload=funcToExecute;
Exercise - 6
Detect Network Change
Solution
Titanium.Network.addEventListener('change', function(e) {Ti.API.info('network changed: ' + e.networkTypeName);Ti.API.info('Reason: ' + e.reason);if (e.online) {Ti.API.info('device is online');} else {Ti.API.info('device is offline');}});
No comments:
Post a Comment