iphone/ipad development, send info to server
Planning 开发者_开发技巧to configure database on server site, and need to send info submitted by user from iphone/ipad to the server. What is the best way of doing it in the xcode?
ASIHTTPRequest might be a good & easy solution. It lets you upload and download files to and from a server... It implements super-easy, a few lines of code... just see the "setup/install" and "how to use" pages here.
It's up to the pages (php for example) on your server how the information should be sent, but I use NSURLConnection
to send information and $_POST['variable']
to read the information server side.
I'll see if I can find an example of how I've used it.
This is my objective-c code to send information to a server:
NSData *data = [NSData dataWithContentsOfFile:localFile];
// setting up the URL to post to
NSString *urlString = [[NSString alloc] initWithFormat:@"%@upload.php", ROOT_URL];
// setting up the request object now
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
[urlString release];
/*
add some header info now
we always need a boundary when we post a file
also we need to set the content type
You might want to generate a random boundary.. this is just the same
as my output from wireshark on a valid html post
*/
NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
/*
now lets create the body of the post
*/
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"ddMMyyyyHHmmss"];
NSDate *now = [[NSDate alloc] init];
NSString *dateString = [format stringFromDate:now];
[format release];
[now release];
NSString *filename = [NSString stringWithFormat:@"recording%@%@.mov", [[UIDevice currentDevice] uniqueIdentifier], dateString];
filename = [filename stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: video/quicktime\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:data]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// now lets make the connection to the web
[[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
精彩评论