2016-02-03 193 views
0

收到一個性反應,我想從服務器連接並接收來自服務器的響應,但我不明白的響應代碼。發送一個HTTP POST請求,並從服務器上的iOS

NSString *post = [NSString stringWithFormat:@"Username=%@&Password=%@",@"_username",@"_password"]; 
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 
NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]]; 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
[request setURL:[NSURL URLWithString:@"https://joomerang.geniusport.com/geniusport/api.php?json"]]; 
[request setHTTPMethod:@"POST"]; 
[request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
[request setHTTPBody:postData]; 
if(conn) { 
    NSLog(@"Connection Successful"); 
} else { 
    NSLog(@"Connection could not be made"); 
} 

這是正確與否,因爲我沒有得到迴應。??

現在的代碼響應?????

NSURLResponse *response=nil; 
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil]; 
NSLog(@"%@",response); 
if (response) { 
    //UIStoryboard *story=[UIStoryboard storyboardWithName:@"Main" bundle:nil]; 
    //TableViewController *obj=[story instantiateViewControllerWithIdentifier:@"table1"]; 
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Login success" message:@"correct Username or Password" delegate:self cancelButtonTitle:@"Done" otherButtonTitles: nil]; 
    [alert show]; 
    //[self.navigationController pushViewController:obj animated:YES]; 
} 
else 
{ 
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Login Failure" message:@"Incorrect Username or Password" delegate:self cancelButtonTitle:@"Done" otherButtonTitles: nil]; 
    [alert show]; 
} 
+0

什麼是'NSLog'的結果呢? – yageek

+0

連接成功 –

+0

我meaned這個'的NSLog(@「%@」,響應);' – yageek

回答

0

所有的代碼是正確的,你只需要添加這在你的info.plist

App Transport Security Setting

  • Allow arbitrary Loads

add red box content in your info.plist

1

你需要獲取的數據:

NSError *error = nil; 
NSURLResponse *response = nil; 
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 

if(responseData) { 
    NSDictionary *results = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:&error]; 
    NSLog(@"res---%@", results); 
} 

,並使用字典繼續使用。

+0

**的NSLog(@ 「%@」 ,responseData1); **爲空 –

+0

任何錯誤是否意味着你可以檢查NSError是否爲零或什麼? –

+0

沒有錯誤,但當我檢查responseData1輸出爲空 –