您可以将 NSURLConnection 与 NSMutableURLRequest 结合使用,如下所示:
//Prepare URL for post
NSURL *url = [NSURL URLWithString: @"https://mywebsite/register.php"];
//Prepare the string for your post (do whatever is necessary)
NSString *postString = [@"username=" stringByAppendingFormat: @"%@&password=%@", uname, pass];
//Prepare data for post
NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
//Prepare request object
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setTimeoutInterval:20];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
//send post using NSURLConnection
NSURLConnection connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
//Connection should never be nil
NSAssert(connection != nil, @"Failure to create URL connection.");
这(使用适合您需要的 postString)应该异步(在您的应用程序的后台)向您的服务器发送一个 POST 请求,并运行您服务器上的脚本。
假设你的服务器也返回了一个答案,你可以听如下:
当创建连接时NSURLConnection connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
,我们告诉连接我们处理服务器在同一个对象中返回的内容,即 self.
当连接返回答案时,将调用以下三个方法(将它们与上面的代码放在同一个类中):
-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response
{
//Initialize received data object
self.receivedData = [NSMutableData data];
[self.receivedData setLength:0];
//You also might want to check if the HTTP Response is ok (no timeout, etc.)
}
-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
[self.receivedData appendData:data];
}
-(void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
NSLog(@"Connection failed with err");
}
-(void)connectionDidFinishLoading:(NSURLConnection*)connection
{
//Connection finished loading. Processing the server answer goes here.
}
请记住,您必须处理 https 连接/请求附带的服务器身份验证。要允许任何服务器证书,您可以依赖以下解决方案(尽管这只是推荐用于快速原型设计和测试):
如何使用 NSURLConnection 与 SSL 连接以获得不受信任的证书?
希望有帮助。