How to use POST method in Appcelerator Titanium for iPhone? - iphone

I have used the POST method in Titanium for Android app and it is working fine. But in iPhoen Simulator it shows a blank array in the server side to be posted.

var req = Titanium.Network.createHTTPClient({
timeout : 15000
});
req.open("POST", url);
req.onload = function(e) {
//YOUR CODE HERE
}
req.onerror = function(e) {
//YOUR CODE HERE
}
req.send(params);
If, server requires json format of data than you can use req.send(JSON.stringify(params)) otherwise you can send it simply.

Related

Unexpected behavior for Facebook Sharing [duplicate]

This question already has an answer here:
Facebook ignoring OG image on first share
(1 answer)
Closed 6 years ago.
First of all hi and thanks in advance to anyone who can help with this because I've been going crazy over this for weeks now.
So I've got a website which lists gif taken from my mobile application (which are then stored on AWS and my visitors ( I haven't found a use for me to have users) can share these gifs on facebook using the facebook sdk.
The problem appears when I try sharing an image for the first time
This is what the share dialog shows the first time I click on my sharing button:
http://i.stack.imgur.com/lNVNF.png
and then I close and reclick the same button and now it works:
http://i.stack.imgur.com/YsDUm.png
Now I've been trying to find a way to make this work on the first sharing attempt but to no avail.
I am using meteor in combination with biasport:facebook-sdk and Amazon S3 for the hosting of my files.
Edit here is the code used:
FRONT SIDE
HTML
<div class="facebook share">
<img src="/gallery/fb.png">
</div>
Javascript
Template.*templateName*.events({
'click .facebook': function(e){
e.preventDefault();
e.stopPropagation();
// this is in a modal so I store the data I need
// (events have photos which in turn contain a url to the gif
var url = Session.get('event').photos[Session.get("id")].url;
FB.ui({
method: 'share',
href: url
});
}
SERVER SIDE
JAVASCRIPT
if(Meteor.isClient) {
window.fbAsyncInit = function() {
FB.init({
appId : 'APP_ID',
status : true,
xfbml : true,
version : 'v2.5'
});
};
}
Edit: I found a manual solution using exec future and curl
so first I added a call to a meteor method on the share that updates the facebook crawler
JAVASCRIPT
Template.*templateName*.events({
'click .facebook': function(e){
e.preventDefault();
e.stopPropagation();
// this is in a modal so I store the data I need
// (events have photos which in turn contain a url to the gif
var url = Session.get('event').photos[Session.get("id")].url;
Meteor.call('updateCrawler', url, function(){
FB.ui({
method: 'share',
href: url
});
});
}
Then I defined my meteor method as such
JAVASCRIPT
Meteor.methods({
updateCrawler: function(url){
var future = new Future();
cmd = 'curl -X POST -F "id=' + url + '" -F "scrape=true" -F "access_token={my_access_token}" "https://graph.facebook.com"';
exec(cmd, function(error){
if (error){
console.log(error);
}
future.return();
});
future.wait();
}
});
it's ugly but since I'd have to wait for the crawler to update and it works I'll leave this here for future use for someone maybe
Edit2:
I did not use og tags at all since I was simply sharing a url to aws directly and not a url to my website
I worked around this problem by calling the Facebook API direct from the server to make it scrape the og data by requesting info on the page. First time round it doesn't have the image cached but second time it does so this workaround does the initial call before sharing.
Use an access token for your facebook app and call the below in an ajax call and await the response before opening share dialog. Replace Google address with your own uri encoded address https://graph.facebook.com/v2.5/?id=http%3A%2F%2Fwww.google.co.uk&access_token=xxxxx
EDIT:
As per comments, here is my server side method for calling this which I use when posts etc are inserted to make the initial call and prompt a scrape from fb:
var getTheOGInfo = function (link)
{
if (!link || link.slice(0, 4).toLowerCase() != "http"){
throw new Meteor.Error("og-info-bad-url", "Function requires an unencoded fully qualified url");
return false;
}
var url = "https://graph.facebook.com/v2.5/{{{{id}}}}?access_token={{{{token}}}}&fields=og_object{id,description,title,type,updated_time,url,image},id,share";
var token = Meteor.settings.private.fb.token;
if (!token){
throw new Meteor.Error("og-info-no-token", "Function requires a facebook token in Meteor.settings.private.fb.token");
return false;
}
var link_id = encodeURIComponent(link);
url = url.replace('{{{{token}}}}', token).replace('{{{{id}}}}', link_id);
var result = HTTP.get(url, {timeout:1000});
return result;
}
Or for your purposes you may not want anything that might be blocking so you could change the last two lines to be aynchronous:
var result = HTTP.get(url, {timeout:1000});
return result;
//Replace with non blocking
HTTP.get(url, {timeout:1000}, function(err, result){console.log('something asynchronous', err, result);});
return true;

Ionic Worklight Page not displaying after HTTP request

I'm having an issue displaying the content in the page after the Worklight http request has been executed.
The weird thing is that when I go to another page and I come back, the content gets displayed. It's like if it needs to be refreshed or something. I can see the console.log() data was received, but page was not refreshed.
This is my code:
$stateProvider.state('accounts', {
url: "/accounts",
templateUrl: 'views/accounts.html',
controller: function($scope, $ionicScrollDelegate, $rootScope){
var req = new WLResourceRequest("/adapters/JavaMQ/bankmq/getAccounts/"+$rootScope.globalReqUserId, WLResourceRequest.GET);
req.send().then(function(resp){
var x2js = new X2JS();
resp.responseText = x2js.xml_str2json(resp.responseText); //to JSON
$scope.reqUserId = resp.responseText['ASI_Message']['Riyad_Bank_Header']['Requestor_User_ID'];
$scope.accountsList = resp.responseText['ASI_Message']['Repeating_Group_Section']['Repeating_Group'];
console.log($rootScope);
})
}
});
UPDATE:
I noticed that I also keep getting the following when I moved the project to Windows (Never happened in my mac)
Deviceready has not fired after 5 seconds
Channel not fired: onCordovaInfoReady
Channel not fired: onCordovaConnectionReady
I don't really know Worklight but the documentation indicate that the send().then() handles both the onSuccess and onFailure.
Maybe the then() is expecting 2 parameters like this:
var request = WLResourceRequest(url, method, timeout);
request.send(content).then(
function(response) {
// success flow
},
function(error) {
// fail flow
}
);
If that doesn't work, can you put a breakpoint at the start of var x2js = new X2JS(); and tell us what happens?

Firefox SDK block content-type

I am developing an add-on for Firefox and i want to block a special kind of requests in content-type.
For example i want to block the application/x-rar content-types and show a message in console.log
You are able to intercept the requests by observing the http-on-examine-response notification event and check getResponseHeader('Content-Type') for application/x-rar.
'use strict';
const {
Ci, Cr
} = require('chrome');
const events = require('sdk/system/events');
events.on('http-on-examine-response', function(event) {
let channel = event.subject.QueryInterface(Ci.nsIHttpChannel);
let contentType = channel.getResponseHeader('Content-Type');
if(contentType === 'applicaiton/x-rar'){
event.subject.cancel(Cr.NS_BINDING_ABORTED);
console.log('Aborted Request', channel.name);
}
});
Best of luck with developing your add-on.

Titanium xhr events not firing

I have been trying to get a simple xhr request to work but for some unknown reasons nothing happens, not even the onerror function fires off.
var xhr = Ti.Network.createHTTPClient();
xhr.onload = function() {
Titanium.API.log('Success');
}
xhr.onerror = function() {
Titanium.API.log('Error');
}
xhr.open("GET","http://www.google.com/");
xhr.send();
I have tried this with a new created project and still no luck. Using little snitch I noticed that a connection is made by the app to the given url ... but still nothing fires off.
What am I missing?
Also I'm developing on an iPhone Simulator.
I don't think there's anything wrong with the XHR request - the Titanium.API.log function takes two arguments, but you're only giving it one, so it's probably just not printing to the console. The Titanium documentation is down at the moment so I can't link you to the correct API, but if you change your code to use Ti.API.info, for example, you should see something printed. This works for me:
var xhr = Ti.Network.createHTTPClient();
xhr.onload = function() {
Titanium.API.info('Success');
}
xhr.onerror = function() {
Titanium.API.info('Error');
}
xhr.open("GET","http://www.google.com/");
xhr.send();

Triggering shouldStartLoadWithRequest with multiple window.location.href calls

Im trying to pass multiple things from a webpage inside a UIWebView back to my iPhone app via the shouldStartLoadWithRequest method of the UIWebView.
Basically my webpage calls window.location.href = "command://foo=bar" and i am able to intercept that in my app no problem. Now if i create a loop and do multiple window.location.href calls at once, then shouldStartLoadWithRequest only appears to get called on once and the call it gets is the very last firing of window.location.href at the end of the loop.
The same thing happens with the webview for Android, only the last window.location.href gets processed.
iFrame = document.createElement("IFRAME");
iFrame.setAttribute("src", "command://foo=bar");
document.body.appendChild(iFrame);
iFrame.parentNode.removeChild(iFrame);
iFrame = null;
So this creates an iframe, sets its source to a command im trying to pass to the app, then as soon as its appended to the body shouldStartLoadWithRequest gets called, then we remove the iframe from the body, and set it to null to free up the memory.
I also tested this on an Android webview using shouldOverrideUrlLoading and it also worked properly!
I struck this problem also and here is my solution that works for me.
All my JavaScript functions use this function __js2oc(msg) to pass data
and events to Objective-C via shouldStartLoadWithRequest:
P.S. replace "command:" with your "appname:" trigger you use.
/* iPhone JS2Objective-C bridge interface */
var __js2oc_wait = 300; // min delay between calls in milliseconds
var __prev_t = 0;
function __js2oc(m) {
// It's a VERY NARROW Bridge so traffic must be throttled
var __now = new Date();
var __curr_t = __now.getTime();
var __diff_t = __curr_t - __prev_t;
if (__diff_t > __js2oc_wait) {
__prev_t = __curr_t;
window.location.href = "command:" + m;
} else {
__prev_t = __curr_t + __js2oc_wait - __diff_t;
setTimeout( function() {
window.location.href = "command:" + m;
}, (__js2oc_wait - __diff_t));
}
}
No, iframe's url changing won't trigger shouldOverrideUrlLoading, at least no in Android 2.2.