如何在服务器上写入数据?

时间:2011-10-20 13:06:11

标签: iphone objective-c ios

我正在制作注册页面,用户可以注册吗? 这是我的代码..............

-(IBAction)btn_log:(id)sender
    {

//NSString* username = nameInput.text;
//NSString* pass = passInput.text;

NSString* firstname = nameInput.text;
NSString* lastname = passInput.text;
NSString* bname = lastInput.text;


NSString *post = 
[[NSString alloc] initWithFormat:@"fname=%@&lname=%@&email=%@",firstname,lastname,bname];

//NSString *post = [[NSString alloc]initWithFormat:@"fname=firstname&lname=lastname&email=bname];

NSData * postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString * postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest * request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.yoursite.com/file.php"]]]; 
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection * conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

if (conn) NSLog(@"Connection Successful");
  }

但它不起作用所以任何人都可以建议我在哪里犯错误。

2 个答案:

答案 0 :(得分:1)

尝试以这种方式可能会帮助你

Nsurl * url = [NSURL URLWithString:[NSString stringWithFormat:@“http://www.yoursite.com/file.php”]]]; nsstring * body = [nsstring stringwithformat:@“%@,%@”,nameinput,paasinput]; nsmutableurlrequest * request = [nsmutablerequest alloc] initwithurl:url];

[request setHTTPMethod:@“POST”]; [请求setValue:@“application / x-www-form-urlencoded”forHTTPHeaderField:@“Content-Type”]; [请求sethttpbody:[body dataysubgebcidubg:asciiiencoding allowlossyconversion:true]]; [请求setValue:postLength forHTTPHeaderField:@“Content-Length”]; [request setHTTPBody:postData]; NSURLConnection * conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

if(conn)NSLog(@“Connection Successful”);

答案 1 :(得分:0)

NSURLConnection * conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

用以下代码替换代码的上一行。可能它会起作用。

NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];