Connect to mysql through Xcode - will appstore allow it? - mysql

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.

Related

Parsing a web page with TFHpple

I'm trying to write a very simple iOS app that will parse a webpage (http://arxiv.org/list/cond-mat/recent) and display a simplified version of it. I chose to use TFHpple to parse this page. I want to get titles of papers and display them in the TableViewController. The HTML container for paper descriptions looks like:
<div class="list-title">
<span class="descriptor">Title:</span> Encoding Complexity within Supramolecular Analogues of Frustrated Magnets
</div>
Function that I use to parse and get the values is the following (thanks to raywenderlich.com):
- (void) loadPapers{
NSURL *papersURL = [NSURL URLWithString:#"http://www.arxiv.org/list/cond-mat/recent"];
NSData *papersHTMLData = [NSData dataWithContentsOfURL:papersURL];
TFHpple *papersParser = [TFHpple hppleWithHTMLData:papersHTMLData];
NSString *papersXpathQueryString = #"//div[#class='list-title']";
NSArray *papersNodes = [papersParser searchWithXPathQuery:papersXpathQueryString];
NSMutableArray *newPapers = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in papersNodes){
Paper *paper = [[Paper alloc] init];
[newPapers addObject:paper];
paper.title = [[element firstChild] content];
}
_objects = newPapers;
[self.tableView reloadData];
}
This function is supposed to parse the entire HTML page and return data into TableView. However, when I try it returns empty objects into the paperNodes array. Basically, the number of the elements is correct (~25), but they're all empty and I am not sure why.
Any help is greatly appreciated! Thanks!
I have rewritten your code with HTMLKit. It looks like this:
NSURL *papersURL = [NSURL URLWithString:#"http://www.arxiv.org/list/cond-mat/recent"];
NSData *papersHTMLData = [NSData dataWithContentsOfURL:papersURL];
NSString *htmlString = [[NSString alloc] initWithData:papersHTMLData encoding:NSUTF8StringEncoding];
HTMLDocument *document = [HTMLDocument documentWithString:htmlString];
NSArray *divs = [document querySelectorAll:#"div[class='list-title']"];
for (HTMLElement *element in divs) {
NSLog(#"%#", element.textContent);
}
Back to your question in the comment:
Could you give some useful links that you find good to learn about HTMLKit?
You can check out the examples on the project's GitHub page. The source code is documented and using it is relatively straightforward. If you have basic HTML & CSS experience then using HTMLKit would be just as easy. Unfortunately there are no other resources it to learn it yet.
Probably the [element firstChild] is returning nil. I suggest you add some NSLog statements to track the data extraction and help you pinpoint the error.

xcode interaction with a html website

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

Scan for images in website - Xcode

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

Loading local html from an array in xcode

I am attempting to load a locally hosted html file into a webview from an array. it looks something like this
_siteAddresses = [[NSArray alloc]
initWithObjects:#"file://localhost/var/mobile/Application/${APP_ID}/First Pentecostal Seminary.app/First_Pentecostal_Seminary/Main.html",...
with the corresponding code being
NSString *urlString = [_siteAddresses
objectAtIndex:indexPath.row];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
self.detailViewController.webView.scalesPageToFit = YES;
[self.detailViewController.webView loadRequest:request];
What am I doing wrong...is it my coding or perhaps the html coding (I believe there may be some java in there)
Two thoughts:
That example file URL doesn't look right. How did you construct that? If it was something from your bundle on your device, I'd expect something more like:
file:///var/mobile/Applications/9E670C3C-C8B1-4B09-AE66-B43F7DB29F4D/First Pentecostal Seminary.app/...
Obviously, you have to programmatically determine this URL by using NSBundle instance method URLForResource or by using the bundle's bundleURL and then adding the appropriate path components.
You should (a) specify the view controller to be the delegate for your web view; and then (b) implement webView:didFailLoadWithError: and look at the error there, and it will inform you what the error was, if any.
For example, I have a file, test.html sitting in my bundle, which I can load into a web view like so:
NSURL *bundleURL = [[NSBundle mainBundle] bundleURL];
NSURL *url = [bundleURL URLByAppendingPathComponent:#"test.html"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
I have set up my view controller as the delegate for the web view and have the following didFailLoadWithError:
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
NSLog(#"%s: %#", __FUNCTION__, error);
}
So, when I tried to load a request with an invalid URL this time (test2.html, which I do not have in my bundle), I get the following error:
2014-02-26 23:35:43.593 MyApp[3531:70b] -[ViewController webView:didFailLoadWithError:]: Error Domain=NSURLErrorDomain Code=-1100 "The requested URL was not found on this server." UserInfo=0x8c32f40 {NSErrorFailingURLStringKey=file:///Users/user/Library/Application%20Support/iPhone%20Simulator/7.0.3/Applications/FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF/MyApp.app/test2.html, NSErrorFailingURLKey=file:///Users/user/Library/Application%20Support/iPhone%20Simulator/7.0.3/Applications/FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF/MyApp.app/test2.html, NSLocalizedDescription=The requested URL was not found on this server., NSUnderlyingError=0x10424c90 "The requested URL was not found on this server."}
Try this code
UIWebView *documentsWebView=[[UIWebView alloc]init];
documentsWebView.delegate=self;
documentsWebView.frame=CGRectMake(0, 0, 1024, 616);
documentsWebView.backgroundColor=[UIColor clearColor];
[self.view addSubview:documentsWebView];
NSString* htmlString = [NSString stringWithContentsOfFile:[_siteAddresses
objectAtIndex:indexPath.row] encoding:NSUTF8StringEncoding error:nil];
[documentsWebView loadHTMLString:htmlString baseURL:nil];

Implementing 'Download to Computer' functionality of browser

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