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
Related
I am making an app which will give me the latest news, and the image. I achieve the text bit by making a scanner like this.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
/* set headers, etc. on request if needed */
[request setURL:[NSURL URLWithString:#"http://stackoverflow.com/questions/22671347/nsuinteger-should-not-be-used-in-format-strings"]];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSScanner *scanner = [NSScanner scannerWithString:html];
NSString *token = nil;
[scanner scanUpToString:#"<p>" intoString:NULL];
[scanner scanUpToString:#"</p>" intoString:&token];
int length = 3;
token = [token substringFromIndex:length];
textView.text = token;
Now I was wondering if I could use the same type of code to scan the website to find the first image and put it an image view. Also it don't have to be same type of code , post what ever you know and any method.
Summary is.
Want a piece of code that will scan a webpage, pick up the first image and place it in a image view.
Thanks for the people who take the time to help me.
THANKS AGAIN!!!
BYE!!!
NSScanner its not a HTML parser only intended for scanning values from NSString object. If you doing the odd scan you probably could get away with it, but it doesn't seem like...
The CORRECT approach is to use Libxml2 library included in Xcode which is only written is C which doesn't have any Objective-C/Swift wrapper. Libxml2 is the XML C parser and toolkit developed for the Gnome project. Alternatively i would recommend using open-source project such as HTMLReader. Its a HTML parser with CSS selectors in Objective-C and Foundation. It parses HTML just like a browser and is all written in Objective-c.
Example (using HTMLReader):
HTMLDocument *document = [HTMLDocument documentWithString:html]; // get your html string
NSLog(#"IMG: %#", [document firstNodeMatchingSelector:#"img"].textContent); // => image returned here
To find images just change the tag to < img > and your set!!
IF your using Libxml2 take a look at HTMLparser.c header file to parse and retrieve HTML ltags
I'm very new to obj-c, and I'm doing this app where you click an annotation, which takes you to the country. I want to connect to MySql with an external php script:
<?php
include("connect.php");
$land = $_GET['land'];
$res = mysql_query("SELECT * FROM lande WHERE name = '$land'");
$row = mysql_fetch_array($res);
$flag = $row['flag'];
echo $flag;
echo $land;
?>
and here is my button in Xcode:
-(void)button:(id)sender {
if (mapView.selectedAnnotations.count == 0)
{
//no annotation is currently selected
return;
}
id<MKAnnotation> selectedAnn = [mapView.selectedAnnotations objectAtIndex:0];
country_title = selectedAnn.title;
UIViewController* Countries = [[UIViewController alloc] initWithNibName:#"Countries" bundle:[NSBundle mainBundle]];
NSString *strUrl = [NSString stringWithFormat:#"http://localhost:8888/app/country.php?land=%#",country_title];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strUrl]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSLog(#"%#",strResult);
[self.view addSubview:Countries.view];
}
How do I print out my results?
and is this at all legal? Will appstore allow this?
Is there another way to do it? I know SQLite but it seems very difficult ... :(
There is no rules against using outside database resources in your application. I use this method all the time to include extra data that is constantly changing that can't be stored locally. However, you do not have a PHP server on your device, so to do this fully you'll need to connect to a remote server.
If you are dead set on doing it all locally might want to read up a bit on SQLite, if you can do MySQL you'll be fine working with SQLite.
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
I am trying to download a mp3 file at a given link using NSURLConnection. However, I usually get time-out errors. Entering the link into the browser shows the default player, however the music file is not loaded either:
However, if I create the following simple HTML file:
<html>
<body>
Download
</body>
</html>
And then load the file into Safari, right click on the Download link, then select Download to Computer (or whathever it's called in English), Safari downloads the file.
Any ideas on how I can implement this in my own app?
I tried using
NSData *data = [NSData dataWithContentsOfURL:url];
and
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *r, NSData *data, NSError *e) { /.../ }];`
without success.
Seems like you're trying to hit a fly with a sledgehammer, using "NSURLConnection".
Try doing something a wee bit more high level such as
NSData * mp3data = [[NSData alloc] initWithContentsOfURL:options:error: ];
(the added benefit here is that you can get useful errors back via the "error:" parameter you pass into the method.
Here's an example on what you need to do:
NSURL* url = [NSURL URLWithString:yourMp3URLString];
//URL of the mp3 file
NSString* fileName = [NSString stringWithFormat:#"%#.mp3", mp3Name];
//NSString with the name of the mp3
NSString* destinationPath = [filePathString stringByAppendingPathComponent:fileName];
//NSString with the filePathString (NSString with path destination, you could
//change it to something like this #"User/Desktop")
//and add the NSString filename to the end of it
//so, if we have like User/Desktop it will become User/Desktop/mp3Name.mp3
NSURLRequest* request = [NSURLRequest requestWithURL:url];
NSURLDownload* download = [[NSURLDownload alloc] initWithRequest:request delegate:self];
[download setDestination:destinationPath allowOverwrite:NO];
//create the URLRequest and Download the mp3 to the destinationPath
I want to add an image in the composer such that when i open the mail composer ,the image should be there in the message body.
I do not want an attachment.
And i also do not want to convert the image to base64.Is there any other way???
Thank you.
hello i have work using below code its work perfectly in iphone and ipad .i have attacha image file using this code. its working code.
- (void)createEmail {
//Create a string with HTML formatting for the email body
NSMutableString *emailBody = [[[NSMutableString alloc] initWithString:#"<html><body>"] retain];
//Add some text to it however you want
[emailBody appendString:#"<p>Some email body text can go here</p>"];
//Pick an image to insert
//This example would come from the main bundle, but your source can be elsewhere
UIImage *emailImage = [UIImage imageNamed:#"myImageName.png"];
//Convert the image into data
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(emailImage)];
//Create a base64 string representation of the data using NSData+Base64
NSString *base64String = [imageData base64EncodedString];
//Add the encoded string to the emailBody string
//Don't forget the "<b>" tags are required, the "<p>" tags are optional
[emailBody appendString:[NSString stringWithFormat:#"<p><b><img src='data:image/png;base64,%#'> </b></p>",base64String]];
//You could repeat here with more text or images, otherwise
//close the HTML formatting
[emailBody appendString:#"</body></html>"];
NSLog(#"%#",emailBody);
//Create the mail composer window
MFMailComposeViewController *emailDialog = [[MFMailComposeViewController alloc] init];
emailDialog.mailComposeDelegate = self;
[emailDialog setSubject:#"My Inline Image Document"];
[emailDialog setMessageBody:emailBody isHTML:YES];
[self presentModalViewController:emailDialog animated:YES];
[emailDialog release];
[emailBody release];
}
hello i have work using below code its work perfectly in iphone and ipad .i have attacha image file using this code. its working code.
And ios 3.0 or later directly insert image at attach in iphone
UIImage * image = [UIImage imageWithContentsOfFile:imagePath];
[composer addAttachmentData:UIImageJPEGRepresentation(itemImage, 1) mimeType:#"image/jpeg" fileName:#"MyFile.jpeg"];
//To Append an attachment:
//Create a string with HTML formatting for the email body
NSMutableString *emailBody = [[NSMutableString alloc] initWithString:#"<html><body>"] ;
//Add some text to it however you want
[emailBody appendString:#"<p>Some email body text can go here</p>"];
//Pick an image to insert
//This example would come from the main bundle, but your source can be elsewhere
NSString *filePath = #"";/*you file path*/
//Convert the file into data
NSData *attachmentData = [NSData dataWithContentsOfFile:filePath];
//Create a base64 string representation of the data using NSData+Base64
NSString *base64String = [attachmentData base64EncodedString];
//Add the encoded string to the emailBody string
//Don't forget the "<b>" tags are required, the "<p>" tags are optional
[emailBody appendString:[NSString stringWithFormat:#"<p><b><img src='data:image/png;base64,%#'> </b></p>",base64String]];
//You could repeat here with more text or images, otherwise
//close the HTML formatting
[emailBody appendString:#"</body></html>"];
NSLog(#"%#",emailBody);
//Create the mail composer window
MFMailComposeViewController *email = [[MFMailComposeViewController alloc] init];
email.mailComposeDelegate = self;
[email setSubject:#"My Inline Document"];
[email setMessageBody:emailBody isHTML:YES];
[self presentModalViewController:email animated:YES];
[email release];
[emailBody release];