Calling of webservice in titanium mobile application code always return response with status code 0 - rest

I am new to titanium appcelerator family. Also I am not sure if somebody has posted the same problem before. I couldn't found it so posting it here.
I am developing one mobile application. And in my application I am trying to call one web service which is hosted on my local environment, but it is always returning response with status code 0 and error message "Can't reach host". So I thought that there should be some problem with my web service that I deployed on remote location. And hence I have tried to call some other web services like twitter, but it's same.. :( It is giving me an error while calling twitter web service also.
I also check for a cross domain policy issue. So I have also tried to set rule on server for web service, but it didn't work out. Following is code snippet and environment details that I am using.
Application type: Mobile
Titanium SDK: 2.1.4 GA
Device: Web Browser
Host Operating System: Windows 7
Titanium Studio: Titanium Studio, build: 2.1.2.201208301612
Files for sample web service which is I am calling is present on following locations:
http://db.tt/XoSCujux (api.php)
http://db.tt/bJG2A5XT (Rest.inc.php)
http://db.tt/Hxt6Oojx (.htaccess)
Code:
//declare the http client object
var xhr = Titanium.Network.createHTTPClient();
//this method will process the remote data
xhr.onload = function() {
//check to see if we are refreshing the data via our
//pull and release mechanism
//create a json object using the JSON.PARSE function
result = JSON.parse(this.responseText);
Ti.API.info(result);
console.log(result);
var msgTitle = "data:";
var msgText = result;
var alertBox = Ti.UI.createAlertDialog({
title: msgTitle,
message: msgText
});
alertBox.show();
};
//this method will fire if there's an error in accessing the remote data
xhr.onerror = function(e) {
//log the error to our titanium developer console
Ti.API.error(this.status + ' - ' + this.statusText);
console.log(this.status + ' - ' + this.statusText);
var msgTitle = "Error : " + this.status;
var msgText = "Error Text : " + this.statusText;
var alertBox = Ti.UI.createAlertDialog({
title: msgTitle,
message: msgText
});
alertBox.show();
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.' + e.error);
};
//open up the recipes xml feed
xhr.open("POST", "http://127.0.0.1/rest_example/api.php?rquest=locations");
//finally, execute the call to the remote feed
xhr.send();
Any help would be really appreciated.

Related

iPhone doesn't connect to the web socket but the simulator does

Physical devices cannot connect to my web socket. I tried it with 3 different phone and with different networks. It works fine with my simulators though. I am not getting an error message apart from the standard "Cannot connect to the server" from socket.io on the client.
I don't know if this is a valid indicator but I also tried using https://www.websocket.org/ with the following parameter:
wss://converzone.htl-perg.ac.at:5134
I am getting a "ERROR: undefined DISCONNECTED" there.
I am using an ubuntu server which runs Ubuntu 16.04. The web socket is from socket.io and I am coding with Swift on the client and with Node.js on the server. This whole thing is running on my school's server.
// Here is an array of all connections to the server
var connections = {};
io.sockets.on('connection', newConnection);
function newConnection(socket) {
console.log(socket.id + " connected.");
socket.on('add-user', function(user) {
connections[user.id] = {
"socket": socket.id
};
});
socket.on('chat-message', function(message) {
console.log(message);
if (connections[message.receiver]) {
console.log("Send to: " + connections[message.receiver].socket);
//io.sockets.connected[connections[message.receiver].socket].emit("chat-message", message);
io.to(connections[message.receiver].socket).emit('chat-message', message);
} else {
console.log("Send push notification")
sendPushNotificationToIOS(message.senderName, message, message.deviceToken, message.sound)
}
});
//Removing the socket on disconnect
socket.on('disconnect', function() {
console.log("The client disconnected");
console.log("The new list of clients is: " + connections)
for (var id in connections) {
if (connections[id].socket === socket.id) {
delete connections[id];
break;
}
}
})
}
Please understand that this problem seems very weird to me. I have changed the AppTransferProtocol in my plist and changed the port from 3000 to 5134. Nothing changed. Tell me what code would seem relevant apart from the (minimal) server code.

$.ajax SOAP request is not working in Phonegap + JQM + IOS 6

Ajax to consume WCF service hosted at server. I already configured and allowed following flag of JQM to use Cross-Domain Requests.
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
The same code is working with Android emulator and Device. I also allowed the url in config.xml file of Phonegap for IOS app.
Also I can browse the same HTML page in Safari and IOS emulator. In both webservice is working fine. The issue occurs when I build and run the phonegap app in IOS emulator or device. The service will not called and success callback of $.ajax is called. I checked the response in success and I found that it is returning the HTML of web service url page (.svc).
I used following code to call SVC using $.ajax
var soapRequest = '<?xml version="1.0" encoding="utf-8"?>'
+ '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">'
+ '<soap:Body>'
+ '<SignIn xmlns="http://tempuri.org/">'
+ '<UserName>' + $.trim($('#txtEmail').val()) + '</UserName>'
+ '<Password>' + $.trim($('#txtPassword').val()) + '</Password>'
+ '<DeviceDetails>' + GetDeviceInfo() + '</DeviceDetails>'
+ '</SignIn>'
+ '</soap:Body>'
+ '</soap:Envelope>';
$.ajax({
beforeSend: function (xhr) {
ShowLoading('Please wait...');
xhr.setRequestHeader("SOAPAction", "http://tempuri.org/IService/SignIn");
}, //Show spinner
complete: function () {
HideLoading();
}, //Hide spinner
url: "http://somedomain/service.svc",
type: "POST",
dataType: "xml",
data: soapRequest,
contentType: "text/xml; charset=\"utf-8\"",
success: function (rcvdata, status) {
alert(rcvdata); // THIS IS GIVING HTML OF SERVICE PAGE
},
error: function (request, status, error) {
alert(request + "\n" + status + "\n" + error);
HideLoading();
}
});
I also tied to change the value of async and processdata option of AJAX but it is always returning the svc service page html. Ajax request status is always 200.
This issue is only occurring in Phonegap IOS app. When I directly open the HTML page in IOS emulator browser then the service is called successfully and I got the valid SOAP response.
I am using Phonegap 2.8.1 and also tried in 2.9.0
Thanks in advance.
Edit --------------
I host the WCF service local environment in IIS then it is working fine and I got the response from service. I also checked and compare the IIS settings in local and live server. Both are same

Facebook share via app loads two popups

The problem can be watched here
http://antipinagroup.com/collections/sac-de-voyage
On sharing via fb app ui loads two popups — feed dialogue and blank page.
Can't get the problem. Any ideas why it happens and how to resolve it?
The code for forming
objFB = {
method: 'feed',
link: document.location.href,
picture: fullPathImage + numimg +".jpg",
name: dataBl.title,
caption: dataBl.title,
description: dataBl['text description']};
_share = _share.replace(/href="javascript:;"/g, 'onclick="postToFeed(); return false;"' );
$( "." + mainBlockClass + " #overlay_" + mainBlockClass ).html( _share );
break;}});
(function(d){FB.init({appId: "151107748411463", status: true, cookie: true});}(document));
function postToFeed() { function callback(response) { /*console.log(response);*/ }FB.ui(objFB, callback);}
All I’m getting when I’m trying you FB share is
An error occurred. Please try again later.
API Error Code: 1
API Error Description: An unknown error occurred
Error Message: kError 1349040: Invalid App ID: The provided app ID is invalid.
I added &show_error=true at the end of the feed dialog URL your page creates as you can see, which is always (OK, make that most of the times) helpful to find errors with FB dialogs.
So first of all check your app id in your code.

Using WebSockets on Samsung Smart TV

My requirement is to have a listening socket in my Samsung Smart TV app, in order to receive events from a device in the same local network.
I've been searching the web for methods to do that and I came across terms like Node.js, Socket.io, websocket. Even though i understand these terms in terms of web development (I think), I am unable to picture a method to open a listening socket in my Samsung Smart Tv App.
Just for the sake of playing around I wrote a TCP Server code on iOS using GCD Async Sockets and thought of connecting it to the smart tv and send a welcome message.
This is the code on my smart tv -
//var wsUri = "wss://echo.websocket.org/";
var wsUri = "ws://192.168.1.116:9898/";
//var output;
var webSocketObj={};
webSocketObj.init = function()
{
//output = document.getElementById("output");
this.testWebSocket();
};
webSocketObj.testWebSocket = function()
{
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen(evt); };
websocket.onclose = function(evt) { onClose(evt); };
websocket.onmessage = function(evt) { onMessage(evt); };
websocket.onerror = function(evt) { onError(evt); };
};
function onOpen(evt)
{
writeToScreen("CONNECTED");
doSend("WebSocket rocks");
}
function onClose(evt)
{
writeToScreen("DISCONNECTED");
}
function onMessage(evt)
{
writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>');
websocket.close();
}
function onError(evt)
{
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function doSend(message)
{
writeToScreen("SENT: " + message);
websocket.send(message);
}
function writeToScreen(message)
{
/* var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);*/
alert('SOCKET HELPER SAYS : '+message);
}
I have a button and I'm calling webSocketObj.init() on the button click.
Logs of my didReadData of the server :
Client says : GET / HTTP/1.1
Log from SmartTv :
[JS ALERT]: Scenewebsocket.handleKeyDown(29443)
[JS ERROR]:
File: file://
Line No: 0
Error Detail:
[JS ALERT]: SOCKET HELPER SAYS : DISCONNECTED
ALSO I tried echoing the message back to the Smart Tv from the server. And this time i got the logs
Client says : GET / HTTP/1.1
Client says : Upgrade: WebSocket
Client says : Connection: Upgrade
Client says : Host: 192.168.1.116:9898
Client says : Origin: file://
Client says : Sec-WebSocket-Key1: 1504l73 8Ew/J 4 ,L7W6
Client says : Sec-WebSocket-Key2: TK2 81d A64Bo7 118 0
I know i'm doing something horribly wrong...what is it? Pls help.
Have you tried socket.io server and client libraries?
We have socket.io server on node.js, and TV can connect to it using socket.io-client library. On 2012 TV it uses websocket. On 2011 TV it uses XHR fallback.
You can use socket.io library to make it easier for yourself to use WebSockets.
You would include a web browser version of socket.io in the samsung tv like this:
<script src="http://*some ip address*/socket.io/socket.io.js"></script>
Where some ip address is the ip address of a nodejs server that you control.
On your server you would need to install NodeJS with the socket.io server version.

Upload video to Facebook from the server

I have a problem when uploading videos to Facebook.
I use Facebook SDK for Android: https://github.com/facebook/facebook-android-sdk to get the access token with the following permissions: "publish_stream","email","video_upload","publish_actions"
Then I send token to the server, which should upload the video. The server tries to upload video using following code:
string fullurl = string.Format("https://graph-video.facebook.com/me/videos?title={0}&description={1}&access_token={2}", HttpUtility.UrlEncode(fileName), HttpUtility.UrlEncode(description), token);
Facebook returns an error:
System.Net.WebException: The remote server returned an error: (400) Bad Request.
at System.Net.WebClient.UploadFile(Uri address, String method, String fileName)
at System.Net.WebClient.UploadFile(String address, String fileName)
But, when I check token with the following link: https://graph.facebook.com/me?access_token=myToken Facebook returns user info. That means that token is valid. But, if this request returns error code, where I can find information about error codes?
This solution works perfectly for some users, for other users it works unstable ( 4 of 6 videos uploading failed. Facebook returns that: "connection closed by remote server"). And have not worked for some users with error: "The remote server returned an error: (400) Bad Request".
What is wrong in my code?
I've solve the problem. I have start using facebook SDK for .NET http://facebooksdk.net/ and it works for me.
Facebook.FacebookClient fb = new FacebookClient(facebookEditTask.facebookToken);
fb.PostCompleted += (o, e) =>
{
if (e.Cancelled || e.Error != null)
{
return;
}
var result = e.GetResultData();
facebookVideoUrl = CreateLinkToVideo(result.ToString());
};
dynamic parameters = new ExpandoObject();
parameters.source = new FacebookMediaStream
{
ContentType = "video/mp4",
FileName = Path.GetFileName(facebookEditTask.FilePath)
}.SetValue(File.OpenRead(facebookEditTask.FilePath));
parameters.message = fbMessage;
Task t = fb.PostTaskAsync("me/videos",
new { message = fbMessage, parameters.source });