2012-11-16 80 views
0

我從以前的項目借閱代碼我已經完成了它的工作。我已經單獨測試了使用jQuery輸出數據的頁面,並且它工作正常,所以我知道這是xcode中的一個問題。在iPhone上使用SBJSON發佈到php頁面的問題

我使用下面的代碼需要包含用於獲取正確的返回數據後數據一個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端和JSON這個空編碼發佈爲{"method":"getWhatsOn"},非常簡單。我的測試php頁面只是獲取這個方法的名稱,並將其打印回正確編碼,即{"SC":"200","data":"getWhatsOn"}。正如我剛纔提到的那樣,它在瀏覽器中使用jQuery,但在PHP中,當請求來自iPhone時,$ _POST ['method']返回null。

回答

0
NSString *Sc= @"200"; 
NSString *[email protected]"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); 

} 
+0

您應該在答案上添加一些解釋。 –

+0

是的,使用這種方法時我仍然會遇到同樣的問題。我的字典是它應該​​如何。只是在發佈字典的機制上出了問題。 – SamRowley