I am communicating to a server on socket via TCP connection in an iPhone application. I have two text fields uTextField (for Username) & pTextField (for password) and now I want to send this request to the server. can any body tell me how can I pass the value of my text fields?
here plz check my code:
UInt8 message[] = "LOGN|rms01,123456|<END>";
CFDataRef data = CFDataCreate(NULL, message, sizeof(message));
CFSocketSendData(s, NULL, data, 0);
CFRelease(data);
NSLog(#"msg sent");
Note: My code is working good as it is, issue is to pass the values of my text fields instead of hard code. here rms01 is username and 123456 is a password LOGN is login identifier & to tell server that query end.
I know this is a stupid question but I am new in iPhone development so please help me
Thanks in advance
NSString can do most of the work for you with stringWithFormat: and dataUsingEncoding::
NSString *username = #"username";
NSString *password = #"password";
NSString *message = [NSString stringWithFormat:#"LOGN|%#,%#|<END>", username, password];
CFDataRef messageData = (CFDataRef)[message dataUsingEncoding:NSUTF8StringEncoding];
CFSocketSendData(s, NULL, messageData, 0);
Note that you do not need to release messageData.
Related
I am using RNCryptor to encrypt a message from a UITextview and send this message. I want to do the reverse action. ie, when the receiver copy the encrypted message from his inbox and copy to the UITextView in the iOS application and when he press decrypt, he wants to see the original message. how can I decrypt the message since it is in the form of NSString not NSData? I tried to convert using following code before the RNCryptor conversion. But I failed.
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
str is the string from the inbox.
This is the encryption and decryption code:
NSData *encryptedData = [RNEncryptor encryptData:data
withSettings:kRNCryptorAES256Settings
password:kPASSWORD
error:&error];
NSData *decryptedData = [RNDecryptor decryptData:datatoDecrypt
withPassword:kPASSWORD
error:&error];
Could you provide the error message by the following code:
if (error) {
NSLog(#"cannot decrypt with error %#", [error description]);
}
First I need to say that I am new to iPhone development, so please I need you to be specific!
I'm developing an application for School scientific project,the question is: How can I insert data into a mysql table from UITextFields on the iPhone?
On my application I have 3 UITextFields, so I need to insert those UITextFields values into the mysql table. It doesn't matter the way you know to do that, I'm in a hurry and I just wanna to put it to work.
1-I working with this PHP code
<?php
if (isset ($_GET["matricula"]))
$matricula = $_GET["matricula"];
else
$matricula = "ELO";
$sql="INSERT INTO chatitems (user, message, matricula) VALUES ('$_GET[user]','$_GET[messages]','$_GET[matricula]')";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
//$sql = "insert into $DB_Table (matricula) values('$matricula');";
$res = mysql_query($sql,$con) or die(mysql_error());
mysql_close($con);
if ($res) {
echo "success";
}else{
echo "faild";
}// end else
?>
And I insert this CODE on my application(Xcode 4.1)
2
- (IBAction)insert:(id)sender
{
// create string contains url address for php file, the file name is phpFile.php, it receives parameter :name
NSString *strURL = [NSString stringWithFormat:#"http://localhost:8888/phpFile.php?name=%#",txtName.text];
//NSString *strURL = [NSString stringWithFormat:#"http://localhost:8888/phpFile.php?name=%#",txtMatricula.text];
// to execute php code
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
// to receive the returend value
NSString *strResult = [[[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding]autorelease];
NSLog(#"%#", strResult);
NSString *cont11 = [NSString stringWithFormat:#"http://localhost:8888/UEUO/insertMT.php?name=%#",txtName.text];
NSString *cont21 = [NSString stringWithFormat:#"http://localhost:8888/UEUO/insertMT.php?matricula=%#",txtMatricula.text];
NSData *cont12 = [NSData dataWithContentsOfURL:[NSURL URLWithString:cont11]];
NSData *cont22 = [NSData dataWithContentsOfURL:[NSURL URLWithString:cont21]];
NSString *cont13 = [[[NSString alloc] initWithData:cont12 encoding:NSUTF8StringEncoding]autorelease];
NSLog(#"%#", cont13);
NSString *cont23 = [[[NSString alloc] initWithData:cont22 encoding:NSUTF8StringEncoding]autorelease];
NSLog(#"%#", cont23);
}
This code works fine for only one UItextField, I need three3.
Repenting: How can I insert the values of three UITextFields into a MySql table using PHP and C++?
Please anything is helpful, if you know how please help me or send me a tutorial or a piece of code!
Your PHP script is looking for 3 parameters passed from a single request.
Your iPhone code is sending 2 different requests with 1 parameter each.
Your iPhone code should be sending 1 request with 3 parameters set, as with this sort of request:
NSString *cont11 = [NSString stringWithFormat:#"http://localhost:8888/UEUO/insertMT.php?name=%#&matricula=%#&message=%#",txtName.text, txtMatricula.text, txtMessage.text];
[NSData dataWithContentsOfURL:[NSURL URLWithString:cont11]];
I should also point out that you haven't sanitized your inputs. That's really bad. Sanitize your inputs.
i have web site that show a text and i update this text every day , i want to show this text on iphone application , how can i get this text from web site from application ?
what should i do ?
thanks
1-> you require to connect with your web server thought HTTP connection.
2-> Make the request to server.
3-> Parse server response that may contain your "Text".
For technical assistance Read below.
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html
I don't recommend this as the best way to obtain a string from your own web server.
This should point you in the right direction, don't expect it to compile cleanly.
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
/* set headers, etc. on request if needed */
[request setURL:[NSURL URLWithString:#"http://example.com/whatever"]];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
NSString *html = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
NSScanner *scanner = [NSScanner scannerWithString:html];
NSString *token = nil;
[scanner scanUpToString:#"<h1>" intoString:NULL];
[scanner scanUpToString:#"</h1>" intoString:&token];
This will capture text from first h1 tag.
The simplest way is to create a REST API. That might sound tough but it's really easy. On the server side, create a new page which holds only the raw text. Usually it's best to keep it there in JSON/XML format, but a simple text will also work. Now from the iPhone, just contact that address and the response data will contain the text. Parsing an existing page is not something I recommend, because changing that page in the future might result in the app not working anymore.
This is a answer quite late but I think it still might help in your future. You can go into parsing the website and that is the right way to do it but I will show you how to do it a different way, this can also be used to read xml, html, .com, anything and also, .rss so it can read RSS Feeds.
Here :
This can get your first paragraph, if you request I will show you how to get the second paragraph and so on.
//This is your URL
NSURL *URL = [NSURL URLWithString:#"URL HERE"];
//This is the data your pulling (dont change)
NSData *data = [NSData dataWithContentsOfURL:URL];
// Assuming data is in UTF8. (dont change)
NSString *string = [NSString stringWithUTF8String:[data bytes]];
//Your textView your not done.
description.text = string;
//Do this with your textview
NSString *webStringz = description.text;
// Leave this
NSString *mastaString;
mastaString = webStringz;
{
NSString *webString2222 = mastaString;
NSScanner *stringScanner2222 = [NSScanner scannerWithString:webString2222];
NSString *content2222 = [[NSString alloc] init];
//Change <p> to suit your need like <description> or <h1>
[stringScanner2222 scanUpToString:#"<p>" intoString:Nil];
[stringScanner2222 scanUpToString:#"." intoString:&content2222];
NSString *filteredTitle = [content2222 stringByReplacingOccurrencesOfString:#"<p>" withString:#""];
description.text = filteredTitle;
}
Title ? Same deal change the <p> to a <title> in RSS <description> and <title>.
Image ? Same deal change the <p> to what ever your RSS or website uses to get a image to find
But remember for both of them when you change the` you see the link which says stringByReplacingOccurences of you have to change that as well.
out then you have to delete this and make your code like this :
/This is your URL
NSURL *URL = [NSURL URLWithString:#"URL HERE"];
//This is the data your pulling (dont change)
NSData *data = [NSData dataWithContentsOfURL:URL];
// Assuming data is in UTF8. (dont change)
NSString *string = [NSString stringWithUTF8String:[data bytes]];
//Your textView your not done.
description.text = string;
NLog(#"%#", string)
//Do this with your textview
NSString *webStringz = description.text;
// Leave this
NSString *mastaString;
mastaString = webStringz;
Now check your log it shows your whole website html or rss code then you scroll and read it and find your image link and check the code before it and change the String Scanner to your needs which is quite awesome and you have to change the stringByReplacingOccurences of.
Like I said images are a bit tricky when you do it with this method but XML Parsing is a lot easier ONCE you learn it , lol. If you request I will show you how to do it.
Make sure :
If you want me to show you how to do it in XML just comment.
If you want me to show you how to find the second paragraph or image or title or something just comment.
IF YOU NEED ANYTHING JUST COMMENT.
Bye have fun with code I provided, anything wrong JUST COMMENT! !!!!
:D
NSString* urlEncode(NSString * url)
{
string inStr = StringFromNSString(url);
CFStringRef inStringRef = CFStringCreateWithCString( kCFAllocatorDefault, inStr.c_str(), kCFStringEncodingUTF8 );
NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)inStringRef,NULL,(CFStringRef)#"!*’();:#&=+$,/?%#[]",kCFStringEncodingUTF8 );
return encodedString;
}
I am using above method to encode url... even though my app is crashing saying
<body>
<div id="content">
<h1>An Error Was Encountered</h1>
<p>The URI you submitted has disallowed characters.</p> </div>
</body>
</html>
terminate called after throwing an instance of 'std::invalid_argument'
what():
Any idea.. What is wrong with my code?
FYI: It is crashing in this method JSONNode jsonObject0 = libJSON::parse( inResponseData );
UPDATED: The server which i am sending message is UNIX server is it causing problem?
You don't need to create the inStr or inStringRef temporary variables. The types NSString* and CFStringRef are "toll free bridge" types. These types are interchangable with just a simple cast.
You can find more information about toll free bridging here: http://www.mikeash.com/pyblog/friday-qa-2010-01-22-toll-free-bridging-internals.html
That said, you can simplify your method to just the following:
-(NSString*) urlEncode
{
NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes( NULL, (CFStringRef)self, NULL, (CFStringRef)#"!*'();:#&=+$,/?%#[]", kCFStringEncodingUTF8 );
return [encodedString autorelease];
}
The above is best implemented as an NSString category (note the use of self as the value to encode).
This works fine for me. I use CFSTR instead of (CFStringRef)#"!*’();:#&=+$,/?%#[]"
- (NSString *)encodedURLParameterString {
NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)self,
NULL,
CFSTR(":/=,!$& '()*+;[]##?"),
kCFStringEncodingUTF8);
return [result autorelease];
}
You can try this
NSString *sampleUrl = #"http://www.google.com/search.jsp?params=Java Developer";
NSString* encodedUrl = [sampleUrl stringByAddingPercentEscapesUsingEncoding:
NSASCIIStringEncoding];
You need to make sure that you're not URL encoding more than you need. If you're going to be using this encoding string as part of an actual URL, then you should know that there are only portions of the URL that are supposed to be encoded, namely the query string (there are other bits as well, but 95% of the time, this has to do with the query).
In other words, your URL should be:
scheme://host/path?<key>=<value>&<key>=<value>
In this, ONLY the stuff inside the angle brackets (<key> and <value>) should be URL encoded.
It was the problem in UNIX server... It was giving wrong data.
NSString *encodedstring = (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(__bridge CFStringRef)yoururlstring,
NULL,
(CFStringRef)#"!*'();:#&=+$,/?%#[]",
kCFStringEncodingUTF8);
this code works perfect
Here is the best way to encode the formatted URLString:
urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
Instead of using below as it has some memory management issues.
NSString *encodedstring = (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(__bridge CFStringRef)yoururlstring,
NULL,
(CFStringRef)#"!*'();:#&=+$,/?%#[]",
kCFStringEncodingUTF8);
I want to decode my string. I have used parsing and get a string from RSS feed. In a string these special characters are not allowed &,<,> in my app. In server side encoding those characters and give it to the string. So now i got the string like,
Actual String : <Tom&Jerry> (only these characters are not allowed in node data & < >).
After Encoding: %3CTom%26Jerry%3E.
But i need to display the string is
<Tom&Jerry>
So how can i decode the string.
Please help me out.
Thanks.
Use the -stringByReplacingPercentEscapesUsingEncoding: method.
[#"%3CTom%26Jerry%3E"
stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Look for
- (NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
Or by example:
NSString *input = #"Hello%20World";
NSString *output = [text stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"%# becomes %#",input,output);
Log: Hello%20World becomes Hello World
I got the answer and my code is,
NSString *currentString =#"%3CTom%26Jerry%3E";
NSString * decodeString = [currentString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
lblTitle.text = decodeString;
Thanks.