I need to post an NSString into a file on my website. I’ve created a file at http://www.mysite.herokuapp.com/newFile.php and need to post data into newFile.php.
I found this Send String to webserver in iOS? earlier, which I thought was perfect, but soon realized was from 2009/2010 and the code wasn’t working. After fiddling with it for a bit, I got the code below, but it doesn’t work.
So there are two parts to this:
First, should I even be posting into a .php file in the first place? Would .txt be easier?
Second, how do I do this on the website end and the iOS end?
Here is the code I’ve put together in iOS:
// Post data onto external server
NSString *post = @"IsThisWorking?";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"https://mysite.herokuapp.com/getLikes.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
you have to handle this on your server.
the method that receives the
NSString– which in your examplegetLikes.php– should save the string to a file on the server.i’m not familial with PHP, but this link might help
php – file write