【发布时间】:2014-02-10 10:54:59
【问题描述】:
我正在做一个项目,我必须将用户的详细信息发送到服务器以在应用程序中注册。我已经完成了 UI,但无法找到如何向用户发送姓名、电话号码、地址等详细信息的解决方案。我需要有人从一开始就指导我完成整个过程。后端已经写好了,是用PHP写的。
【问题讨论】:
标签: php ios iphone web-services
我正在做一个项目,我必须将用户的详细信息发送到服务器以在应用程序中注册。我已经完成了 UI,但无法找到如何向用户发送姓名、电话号码、地址等详细信息的解决方案。我需要有人从一开始就指导我完成整个过程。后端已经写好了,是用PHP写的。
【问题讨论】:
标签: php ios iphone web-services
如果您已经编写了后端,您可以在 iOS 7 中通过NSURLSession 向服务器发送数据并返回。下面的示例将以 JSON 格式向服务器发送用户名和密码。
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:@"URL to which you want to send data"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];
NSDictionary *data =@{"userName":"Abc","password","xyz"}
NSData *postData = [NSJSONSerialization dataWithJSONObject:data options:0 error:&error];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// write logic after geting response from the server
}];
[postDataTask resume];
【讨论】:
100% 有效
NSString *post = [NSString stringWithFormat:@"username=%@&password=%@",@"Raja",@"12345"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[post length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://localhost/promos/index.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:request delegate:self];
if( theConnection ){
// indicator.hidden = NO;
mutableData = [[NSMutableData alloc]init];
}
你的 PHP 代码
<?php
$username = $_POST['username'];
$password=$_POST['password'];
echo $username;
?>
【讨论】: