2013-12-16 42 views
0

所以我正在創建一個註冊頁面。但是我很難弄清楚如何將用戶名字符串作爲參數並將其放入參數部分。不用硬編碼。現在它的硬編碼爲[email protected]和password1。我希望能夠將上面輸入的所有內容放入參數部分,以便將其發送到服務器。如何在Xcode中創建註冊頁面?

任何幫助,將不勝感激!謝謝。
我的代碼如下:

- (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\":\"[email protected]\",\"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

不要嘗試「手動」構建JSON數據。這很容易出錯,因爲 字符串可能包含必須在JSON中轉義的字符。

更好地創造一個字典,並使用 NSJSONSerialization

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

太謝謝你了!這正是我需要的。如果我能用最後一個問題麻煩你。我已經在這裏發佈了。我似乎無法登錄。不知道我做錯了什麼。 http://stackoverflow.com/questions/20622006/how-can-i-create-a-login-page-in-xcode – paintball247