IOS HttpPost无法正常工作

时间:2014-05-11 20:26:26

标签: ios

我正在尝试为注册用法发送多个参数。这是我的发布数据代码:

-(void)PostRegistrationData:(NSString *)userEmail :(NSString *)Password{

    NSDictionary *params = @{
                             @"username":@"something",
                             @"password":@"aFilter",
                             @"email":@"aCategory",
                             @"type":@"aCategory",
                             @"request_type":@"aCategory"
                             };

    /* We iterate the dictionary now
     and append each pair to an array
     formatted like <KEY>=<VALUE> */
    NSMutableArray *pairs = [[NSMutableArray alloc] initWithCapacity:0];
    for (NSString *key in params) {
        [pairs addObject:[NSString stringWithFormat:@"%@=%@", key, params[key]]];
    }
    /* We finally join the pairs of our array
     using the '&' */
    NSString *requestParams = [pairs componentsJoinedByString:@"&"];



    NSData *postData = [requestParams dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://teknofolk.com/spisrett_admin/slave/signup.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;
          NSMutableData *mutableData = [[NSMutableData alloc]init];

    }
}

但是没有插入数据。我错过了什么吗?

2 个答案:

答案 0 :(得分:0)

您有多种选择要使用。

第一个选项:

NSURLResponse *res = nil;
NSError *err = nil;
NSData *retData = [NSURLConnection sendSynchronousRequest:request returningResponse:&res error:&err];

(此选项还有async方式。)

或者您也可以按照您的代码继续操作:

NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];

并且请求将是异步的,并将调用此方法(您需要此视图控制器响应 NSURLConnectionDelegateNSURLConnectionDataDelegate):

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse 
*)response
{

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{

}

答案 1 :(得分:0)

这是我在参数中的错误。

NSDictionary *params = @{
                         @"username":@"something",
                         @"password":@"aFilter",
                         @"email":@"aCategory",
                         @"type":@"aCategory",
                         @"request_type":@"aCategory"
                         };

只需处理这个:

                         @"type":@"1",
                         @"request_type":@"2"
                         };

在我的插入中,我在类型和请求类型上传递了错误的值。感谢所有人