如何在Xcode中创建注册页面?

时间:2013-12-16 21:41:32

标签: .net objective-c json xcode post

所以我正在创建一个注册页面。但是我无法弄清楚如何将用户名的STRING作为例子并将其放在参数部分中。没有硬编码。现在它的硬编码为username@yahoo.com和password1。我希望能够将上面输入的所有内容放入参数部分,以便将其发送到服务器。

任何帮助将不胜感激!谢谢。
我的代码如下:

- (IBAction)signUp:(id)sender {

if ([userName.text isEqualToString:@""] || [email.text isEqualToString:@""] || [emailPublic.text isEqualToString:@""] ||[password.text isEqualToString:@""] || [passwordHint.text isEqualToString:@""] || [avatar.text isEqualToString:@""] || [sex.text isEqualToString:@""] || [dob.text isEqualToString:@""]) {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Oops!" message:@"Please fill in all the fields!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
    return;
}

   NSURL *url = [NSURLURLWithString:@"http://WEBSITEHERE/api/users/AuthenticateUser"];
   NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

   NSString *parameters = @" {\"userName\":\"username@yahoo.com\",\"password\":\"password1\"}";

    NSLog(@"PARAMS = %@", parameters);   

    NSData *data = [parameters dataUsingEncoding:NSUTF8StringEncoding];    

    [request setHTTPMethod:@"POST"];

    [request setValue:@"text/plain" forHTTPHeaderField:@"Accept"];

    [request setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];

    [request setHTTPBody:data];     

    NSURLResponse *response = nil;

    NSError *error = nil;    

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

   NSString *responseString = [[NSString alloc]initWithData:result encoding:NSUTF8StringEncoding];    

NSLog(@"RESULT = %@", responseString);
 }

1 个答案:

答案 0 :(得分:1)

不要尝试“手动”构建JSON数据。这很容易出错,因为 字符串可能包含必须在JSON中转义的字符。

更好地创建字典并使用 NSJSONSerialization

NSDictionary *params = @{@"userName": userName.text, @"password": password.text};
NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];