Since iOS 6 has a bug with GeoLocation/WatchPosition to obtain the users position, I am implenting in xcode the locationManager and get the coordinates.
But, I want to use these coords in a local HTML (webView) file.
Is it possible to use,send or call the coords from locationManager to the HTML / JavaScript file?
EDIT:
I thought about a possible solution... cookies... can that be done because I can not get a output in my code below:
EDIT 2:
Yes it can... I adjust the code below and it works. Important is the Cookie domain and path option so webView (HTML) can get the cookie.
But if someone knows a better solution, please let me know, i like to learn!
- (void)applicationdidBecomeActive {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
...
NSLog(#"%#", DevicePosition);
NSDictionary *newCookieDict = [NSMutableDictionary
dictionaryWithObjectsAndKeys:
#".^filecookies^", NSHTTPCookieDomain,
#"DevicePos", NSHTTPCookieName,
#"/", NSHTTPCookiePath,
DevicePosition, NSHTTPCookieValue,
//#"2012-01-01 12:00:00 -0100", NSHTTPCookieExpires,
nil];
//create a new cookie
NSHTTPCookie *cookie = [NSHTTPCookie
cookieWithProperties:newCookieDict];
//add the new cookie
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
// dev cookie controle
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [cookieJar cookies]) {
NSLog(#"%#", cookie);
}
HTML file:
<script type="text/javascript">
function getCookie(name) {
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
</script>
There is a simple way to soluve your question.
You can use WebViewJavascriptBridge to 'populate' a Objective C's method to webview, so your html page can access that method via window.xxx to invoke the method implemented in Objective C.
Please take a look at https://github.com/marcuswestin/WebViewJavascriptBridge
Related
I am trying to implement an application that includes downloading files from Dropbox. It looks like there is a simple straightforward framework that does that (CloudRail). But the codes crashes when I try to work with the file downloaded (in this case an image), here is the example:
self.dropboxInstance = [[Dropbox alloc] initWithClientId:self.authDic[#“————“] clientSecret:self.authDic[#“————“]];
id returnObject = [self.dropboxInstance downloadWithFilePath:#“/pictures/001.png“];
UIImage * image = [UIImage imageWithData:object]; // CRASH HERE
I checked the network and disk activity through Xcode tools and the download is performed correctly, so I believe it has something to do with the return of the download function.
First of all, the return type of the method is an NSInputStream, that can be used to read the contents of the file you downloaded.
The reason why the code is not working is because you are treating it as an NSData type.
So the solution would be to first read all the content from the stream received as return, store it in an NSData object and then create an UIImage from the data.
self.dropboxInstance = [[Dropbox alloc] initWithClientId:self.authDic[#“————“] clientSecret:self.authDic[#“————“]];
id returnObject = [self.dropboxInstance downloadWithFilePath:#“/pictures/001.png“];
//NEW CODE
NSInputStream * inputStream = returnObject;
[inputStream open];
NSInteger result;
uint8_t buffer[1024]; // buffer of 1kB
while((result = [inputStream read:buffer maxLength:1024]) != 0) {
if(result > 0) {
// buffer contains result bytes of data to be handled
[data appendBytes:buffer length:result];
} else {
// The stream had an error. You can get an NSError object using [iStream streamError]
if (result<0) {
[NSException raise:#"STREAM_ERROR" format:#"%#", [inputStream streamError]];
}
}
}
//END NEWCODE
UIImage * image = [UIImage imageWithData:data]; // NO CRASH ANYMORE :)
The above code is used to read from the stream in a procedural way (will block the thread). To read from the stream asynchronously refer to this other answer (Stream to Get Data - NSInputStream). Hope this helped.
I would like write a small program, which send a string to a Website und get the answer string back.
It's about the following site: http://www.pandorabots.com/pandora/talk?botid=ec8b3be33e34bf73
Programm send string to the text field on the website "Frage: ..."
Programm get back the string after "Brother B!:"
It is a cocoa application for OS X.
-(BOOL)getStringFromWebView:(NSString*)frage
{
//----------------Put the question (frage) into the text field on the web page
if (frage.length != 0) {
//create js strings
NSString *loadUsernameJS = [NSString stringWithFormat:#"var inputFields = document.querySelectorAll(\"input[type='text']\"); \
for (var i = inputFields.length >>> 0; i--;) { inputFields[i].value = '%#';}", frage];
//autofill the form
[self.webView stringByEvaluatingJavaScriptFromString: loadUsernameJS];
}
//-------------Press 'return' to send the message
//PROBLEM: Webview is not active. It do not work...
CGEventRef push = CGEventCreateKeyboardEvent(NULL, 0x24, true);
CGEventRef release = CGEventCreateKeyboardEvent(NULL, 0x24, false);
CGEventPost(kCGHIDEventTap, push);
CGEventPost(kCGHIDEventTap, release);
//I tried this to focus the web view:
//[self.webView stringByEvaluatingJavaScriptFromString:#"document.getElementById(\"input\").setFocus();"];
//----------get response from web page (work!):
WebFrame *frame = [self.webView mainFrame];
WebDataSource *source = [frame dataSource];
NSData *data = [source data];
NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
// NSLog(#"%#",str);
NSArray *woerter1 = [str componentsSeparatedByString: #"<I>Brother B!</I>: "];
NSArray *woerter2 = [woerter1[1] componentsSeparatedByString: #"<form method=\"POST\">"];
self.out3.stringValue = woerter2[0];
return true;
}
Actually i don't really know how to do this... Please help me!
you can load your web page in WebView/IUWebView object and interact with it by JavaScript bridge library. You can use this library link to send to JavaScript a message from native application.
Next you can use JavaScript at html-client-side to manage this message and execute the form.
Cheers
I'm looking for a free tool or dlls that I can use to write my own code in .NET to process some web requests.
Let's say I have a URL with some query string parameters similar to http://www.example.com?param=1 and when I use it in a browser several redirects occur and eventually HTML is rendered that has a frameset and a frame's inner html contains a table with data that I need. I want to store this data in the external file in a CSV format. Obviously the data is different depending on the querystring parameter param. Let's say I want to run the application and generate 1000 CSV files for param values from 1 to 1000.
I have good knowledge in .NET, javascript, HTML, but the main problem is how to get the final HTML in the server code.
What I tried is I created a new Form Application, added a webbrowser control and used code like this:
private void FormMain_Shown(object sender, EventArgs e)
{
var param = 1; //test
var url = string.Format(Constants.URL_PATTERN, param);
WebBrowserMain.Navigated += WebBrowserMain_Navigated;
WebBrowserMain.Navigate(url);
}
void WebBrowserMain_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
if (e.Url.OriginalString == Constants.FINAL_URL)
{
var document = WebBrowserMain.Document.Window.Frames[0].Document;
}
}
But unfortunately I receieve unauthorizedaccessexception because probably frame and the document are in different domains. Does anybody has an idea of how to work around this and maybe another brand new approach to implement functionality like this?
Thanks to the Noseratio's comments I managed to do that with the WebBrowser control. Here are some major points that might help others who have similar questions:
1) DocumentCompleted event should be used. For Navigated event body of the document is NULL.
2) Following answer helped a lot: WebBrowserControl: UnauthorizedAccessException when accessing property of a Frame
3) I was not aware about IHTMLWindow2 similar interfaces, for them to work correctly I added references to following COM libs: Microsoft Internet Controls (SHDocVw), Microsoft HTML Object Library (MSHTML).
4) I grabbed the html of the frame with the following code:
void WebBrowserMain_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (e.Url.OriginalString == Constants.FINAL_URL)
{
try
{
var doc = (IHTMLDocument2) WebBrowserMain.Document.DomDocument;
var frame = (IHTMLWindow2) doc.frames.item(0);
var document = CrossFrameIE.GetDocumentFromWindow(frame);
var html = document.body.outerHTML;
var dataParser = new DataParser(html);
//my logic here
}
5) For the work with Html, I used the fine HTML Agility Pack that has some pretty good XPath search.
Im looking for the equivalent of "tail -f" that runs in a browser using html5 or javascript.
A solution would need a client side code written in HTML5/websockets/javascript and a back-end server side application. Im looking for one in c# but i'm willing to rewrite it from php or python.
This is the only thing that i've seen that comes close is
http://commavee.com/2007/04/13/ajax-logfile-tailer-viewer/
However, modern browsers have WebSockets which makes the problem much simpler.
http://www.websocket.org/echo.html
Ideally, I would like to have some of the capabilities of BareTail
http://www.baremetalsoft.com/baretail/
Such as Color Coding of lines, sorting and multi-file tabbing.
I have located a similar posting where someone is looking for windows based log file programs
https://stackoverflow.com/questions/113121/best-tail-log-file-visualization-freeware-tool
Anyone have any suggestions?
It is not exactly like tail but the live logs feature of https://log4sure.com does allow you to monitor your client side logs realtime. You would have to setup and do the logs appropriately as you would do for tailing, but you can see all the logs with extra information about your client, example browser, os, country etc. You can also create your own custom logs to log stuff. Checkout the demo on the site to get a better idea.
The setup code is really easy, and the best part is, its free.
// set up
var _logServer;
(function() {
var ls = document.createElement('script');
ls.type = 'text/javascript';
ls.async = true;
ls.src = 'https://log4sure.com/ScriptsExt/log4sure-0.1.min.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ls, s);
ls.onload = function() {
// use your token here.
_logServer = new LogServer("use-your-token-here");
};
})();
// example for logging text
_logServer.logText("your log message goes here.")
// example for logging error
divide = function(numerator, divisor) {
try {
if (parseFloat(value) && parseFloat(divisor)) {
throw new TypeError("Invalid input", "myfile.js", 12, {
value: value,
divisor: divisor
});
} else {
if (divisor == 0) {
throw new RangeError("Divide by 0", "myfile.js", 15, {
value: value,
divisor: divisor
});
}
}
} catch (e) {
_logServer.logError(e.name, e.message, e.stack);
}
}
// another use of logError in window.onerror
// must be careful with window.onerror as you might be overwriting some one else's window.onerror functionality
// also someone else can overwrite window.onerror.
window.onerror = function(msg, url, line, column, err) {
// may want to check if url belongs to your javascript file
var data = {
url: url,
line: line,
column: column,
}
_logServer.logError(err.name, err.message, err.stack, data);
};
//example for custom logs
var foo = "some variable value";
var bar = "another variable value";
var flag = "false";
var temp = "yet another variable value";
_logServer.log(foo, bar, flag, temp);
While I wish it had better JSON object prettification for live tailing and historical logs, the following JS client works and supports your server-side requirement also:
https://github.com/logentries/le_js/wiki/API
<html lang="en">
<head>
<title>Your page</title>
<script src="/js/le.min.js"></script>
<script>
// Set up le.js
LE.init('YOUR-LOG-TOKEN');
</script>
</head>
.....
<script>
// log something
LE.log("Hello, logger!");
</script>
Personally to get the above code to work however, I've had to add the following line of code just above LE.init('YOUR-LOG-TOKEN'):
window.LEENDPOINT = 'js.logentries.com/v1'
.. Alternatively, Loggly may be a fit as well: https://www.loggly.com/docs/javascript/
I am writing a Flash app in Flex Builder 3.
I have a problem. I need the URL of the place where the Flash app has been embedded.
mx.core.Application.application.url
This gives me the address of the original swf file, but I actually need the URL of the HTML file where this SWF has been embedded.
is there a way ???
thanks!
Ali
You have 2 options.
in flex:
private function initApp():void {
browserManager = BrowserManager.getInstance();
browserManager.addEventListener(BrowserChangeEvent.URL_CHANGE, showURLDetails);
browserManager.init("", "Welcome!");
}
and the listener
private function showURLDetails(e:BrowserChangeEvent):void {
var url:String = browserManager.url;
baseURL = browserManager.base;
fragment = browserManager.fragment;
previousURL = e.lastURL;
fullURL = mx.utils.URLUtil.getFullURL(url, url);
port = mx.utils.URLUtil.getPort(url);
protocol = mx.utils.URLUtil.getProtocol(url);
serverName = mx.utils.URLUtil.getServerName(url);
isSecure = mx.utils.URLUtil.isHttpsURL(url);
}
That code works both on the server and on Local host.
if that does not work for you (upload the error here first) but you can also create a JS function that will return the URL and have flex call this function.
my comment is unreadable so here it is as an answer.
The code inside SWFObject makes flash act alittle wacky when it comes to the browser manager.
the solution is inside history.js (first attach it to the HTML if you didn't)
Then, comment out these lines of code.
if (players.length == 0 || players[0].object == null) {
var tmp = document.getElementsByTagName(‘embed’);
players = tmp;
}
And this one
if (player == null || player.object == null) {
player = document.getElementsByTagName(‘embed’)[0];
}
This should solve your problem.