在iPhone上使用SBJSON发布到php页面的问题

时间:2012-11-16 12:44:13

标签: iphone xcode json sbjson

我正在借助我之前完成的项目中的代码。我已经分别测试了使用jQuery输出数据的页面,它运行正常,所以我知道这是xcode中的一个问题。

我使用以下代码,该代码采用包含用于获取正确返回数据的post数据的NSDictionary:

-(NSDictionary *)loadData:(NSDictionary *) sendDict{
    SBJsonWriter *writer = [SBJsonWriter new];
    NSString * jsonData = [writer stringWithObject:sendDict];
    NSString * getString = [NSString stringWithFormat:@"json=%@", jsonData];

    NSData *requestData = [NSData dataWithBytes: [getString UTF8String] length: [getString length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"http://divisi.co.uk/YTA/custom_api.php"]];
    [request setHTTPMethod: @"POST"];
    [request setHTTPBody: requestData];

    NSData *returnData = [ NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];

    NSLog(@"Returned Json: %@", returnString);

    // decoding the json
    NSDictionary *loginArray = [NSDictionary alloc];
    loginArray = [returnString JSONValue];

    if([[loginArray objectForKey:@"SC"] isEqualToString:@"200"]){
        return [loginArray objectForKey:@"data"];
    }
    else{
        return [loginArray objectForKey:@"error_message"];
    }
}

当我发送帖子请求时,它在php端找到null,而这个编码要发布的json是{"method":"getWhatsOn"},非常简单。我的测试php页面只获取此方法名称并将其打印回正确编码,即{"SC":"200","data":"getWhatsOn"}。正如我所提到的,它使用jQuery在浏览器中工作,但在php中,$ _POST ['method']在请求来自iPhone时返回null。

1 个答案:

答案 0 :(得分:0)

NSString *Sc= @"200";
 NSString *dataD=@"getWhatsOn";
 NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary];
 [dictionnary setObject:Sc forKey:@"firstString"];
 [dictionnary setObject:dataD forKey:@"secondfield"];

 NSError *error = nil;
 NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary
 options:kNilOptions
 error:&error];   

 NSString *urlString = @"your URL";
 NSURL *url = [NSURL URLWithString:urlString];

 // Prepare the request
 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
 [request setHTTPMethod:@"POST"];
 [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
 [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
 [request setValue:@"json" forHTTPHeaderField:@"Data-Type"];
 [request setValue:[NSString stringWithFormat:@"%d", [jsonData length]]  forHTTPHeaderField:@"Content-Length"];
 [request setHTTPBody:jsonData];    

 NSError *errorReturned = nil;
 NSURLResponse *theResponse =[[NSURLResponse alloc]init];
 NSData *data = [NSURLConnection sendSynchronousRequest:request
 returningResponse:&theResponse
 error:&errorReturned];
 if (errorReturned) 
 {
 //...handle the error
 }
 else 
 {
 NSString *retVal = [[NSString alloc] initWithData:data
 encoding:NSUTF8StringEncoding];
 NSLog(@"%@", retVal);

 }