XCode GET POST WebServer - html

I'm beginner from Xcode. I have to do an application that get and send data from embedded webserver that I designed in a microcontroller MICROCHIP.
Now I'm able to get information from webserver ( In my webserver I have a /status.xml file where I have all the dynamic variables)
Now I am not able to click a button. The HTML code to click a button is
onmousedown="newAJAXCommand('buttons.cgi?btn=1')"
In my webserver I have a file buttons.cgi.
My target is designed a button in Xcode that he does this action
I tried to use NSMutableURLRequest class and SetHTTPMethod:#"GET" or #"POST" but this code doesn't work
NSString *post = #"btn=1";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES ];
NSString *Get_lenght = [NSString stringWithFormat:#"%d",[postData length]];
NSURL *serviceURL = [NSURL URLWithString:#"http://mywebserver.com/buttons.cgi?"];
NSMutableURLRequest *serviceRequest = [NSMutableURLRequest requestWithURL:serviceURL];
[serviceRequest setValue:Get_lenght forHTTPHeaderField:#"Content-type"];
[serviceRequest setHTTPMethod:#"POST"];
[serviceRequest setHTTPBody:postData];

There are multiple errors in the codes:
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES ];
Why don't you use UTF-8 ?
NSString *Get_lenght = [NSString stringWithFormat:#"%d",[postData length]];
[serviceRequest setValue:Get_lenght forHTTPHeaderField:#"Content-type"];
You can't set Content-Type as an integer.
Last, you didn't send out the NSMutableURLRequest. To send out the request, use :
NSString *response;
NSError *error;
[NSURLConnection sendSynchronousRequest:serviceRequest returningResponse:&response error:&error];
where response will contain the response data, if you need it; and the error will contain error during request & response, if there is any error.

Related

iOS 8.0 NSAttributedString init with HTML file crashes

I am trying to initialize an attributed string with HTML file contents, as following:
NSMutableAttributedString *attrStr = [[[NSAttributedString alloc] initWithFileURL:[NSURL fileURLWithPath:chapterPath]
options:#{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType}
documentAttributes:nil error:nil] mutableCopy];
and it does work with iOS7.1 and iOS8.1 and up, but something goes wrong with iOS8.0:
libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: vector
Is this initialization method broken in iOS8.0? Any workaround?
BTW, I have tried to parse an RTF file and, with iOS8.0, it fails to collect any font information.
Did you try this?.
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfFile:chapterPath options:NSDataReadingUncached error:&error];
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData: data options:#{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:&attributes error:nil];
Init with HTML for NSAttributedString is on main thread only. If you doing that in background be ready to crash.

Parsing JSON with NSJSONSerialization: Error 3840 - Data Corrupted?

I've read many Q/As on this problem but couldn't find an answer that fits my situation.
I retrieve a JSON response from a REST service I've created in PHP. This is my code:
NSURLResponse *response = nil;
NSError *theError1 = nil;
NSError *theError2 = nil;
NSURL *webServiceUrl = [NSURL URLWithString:#"http://..."];
NSURLRequest *request = [NSURLRequest requestWithURL:webServiceUrl cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30];
NSData *theData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&theError1];
NSString *dataString = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];
NSLog(#"%#", dataString);
id json = [NSJSONSerialization JSONObjectWithData:theData options:NSJSONReadingAllowFragments | NSJSONReadingMutableContainers error:&theError2];
if (theError2 != nil)
NSLog(#"%#", theError2);
When I invoke the REST call in the browser, I see the following response, which seems identical to what XCode logs:
{
"Name": "REST Service",
"Product": "REST Test",
"Version": "1.0.0.0",
"Copyright": "2013 Test Company"
}
When I execute above code, however, the following error is created and logged:
Error Domain=NSCocoaErrorDomain Code=3840 "The data couldn’t be read because it has been corrupted." (Invalid value around character 3.) UserInfo=0x100547430 {NSDebugDescription=Invalid value around character 3.}
What am I doing wrong?
OK, as always, checking the actual data instead of the string representation pays - thanks #Bavarious.
It turns out that the PHP script(s) in charge of creating the JSON were all "UTF8 with BOM", so PHP returned a BOM for every script involved.
Once I changed all the PHP files to "UTF8 without BOM" everything seems to be fine - need to test this on the MAC though.
Sorry to interrupt, keep up the good work.
(#Bavarious: If you'd like to write an answer, I'd be happy to upvote and accept it, as you pointed me to the solution).
Was able to parse the JSON now as expected. Making a mental note to always double-check the text file encoding.
NSURL *theURL = [NSURL URLWithString:#"http://yourdataurl"];
NSMutableURLRequest *storeRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:storeRequest queue:queue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!connectionError) {
NSError *error;
NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *theData = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:theData options:0 error:&error];
if (!jsonResponse || error)
{
NSLog(#"Error");
}
else
{
// Everything is ok..
}
}
}];

Encoded NSData for a url not saving to the documents directory

I'm trying to save a html page locally on the iPhone's documents directory so I can load the page if the phone is in an offline state
My issue is when I call my NSData object directly to be written to file all the raw data is saved in a file in the documents directory.
But as soon as I cast my NSData to a NSString using encoding it stops writing the file in the documents directory. But when I print my content object it logs out the correct data. I just want that to be saved to a file.
NSURL *url = [NSURL URLWithString:#"http://anyurl"];
NSData *urlHtmlData = [NSData dataWithContentsOfURL:url];
NSString *myString = [[NSString alloc]initWithData:urlHtmlData encoding:NSUTF8StringEncoding];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:#"index.html"];
[myString writeToFile:fileName atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];
What could be causing the content to stop writing to my file?
Or if anyones got a better solution to view offline webpages rather than saving it to the documents directory?
Thanks
There could be a few things wrong with this. One: You don't use stringWithFormat: to append a path component. NSString has a method for that:
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:#"index.html"];
Two: NSStringEncodingConversionAllowLossy is part of an enum that is not defined for writeToFile:, so by using it, you're actually specifying NSASCIIStringEncoding without realizing it. In my opinion, just use NSUTF8StringEncoding instead.
Also, NSString *content = [[NSString alloc]initWithFormat:#"%#", myString]; does absolutely nothing except duplicate myString. Erase that line and just use [myString writeToFile:....

How to read a JSON file using the NSJSONSerialization Class Reference?

I need to read a JSON file using the NSJSONSerialization Class Reference, and all the examples that I have found about the use of this class read the content from the webpage itself, instead of reading from a JSON file that has been previously created.Anyone knows how to parse from a JSON file using that class? Thanks.
Simple, quick'n'dirty example:
NSString *jsonPath = [[NSBundle mainBundle] pathForResource:#"foobar"
ofType:#"json"];
NSData *data = [NSData dataWithContentsOfFile:jsonPath];
NSError *error = nil;
id json = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
NSLog(#"JSON: %#", json);

App is not updating database when string contains spaces

I ran into a weird problem. I built a mysql database where the user can store his contacts through an app. He just adds his contact information by clicking on a button. Then, the data is added to the database.
However, when the contact's information has spaces between his first name, last name or number the app refuses to accept the data. I dont get an error message or anything like that, but I also dont get any confirmation. The record does not exist in the database.
There is no problem with my php file (The file is definitely correct, I got it checked here, twice).
Here is my code:
NSString *strURL = [NSString stringWithFormat:#"http://www.abc.com/phpFile.php?number=%#&name=%#&lastname=%#", number, firstName, lastName];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSLog(#"%#", strResult);
The space character is not allowed in a URI. Use %20 to encode the space. There are other characters that are also not allowed as part of the URI. Look up URI encoding.
NSString *strURL = [NSString stringWithFormat:#"http://www.abc.com/phpFile.php?number=%#&name=%#&lastname=%#", number, firstName, lastName];
strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSLog(#"%#", strResult);