0

我从以前的项目中借出代码,我已经完成了它完美的工作。我已经单独测试了使用 jQuery 输出数据的页面,它工作正常,所以我知道这是 xcode 中的一个问题。

我正在使用以下代码,它采用一个包含用于获取正确返回数据的发布数据的 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 中,当请求来自 iPhone 时,$_POST['method'] 返回 null。

4

1 回答 1

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);

 }
于 2012-11-16T12:52:41.500 回答