2013-03-31 51 views
1

我試圖在服務器上的文本文件中的服務器上上傳label.text,這是我的代碼。它沒有顯示任何錯誤,但在服務器上創建了文件,但沒有文本。請幫忙。將label.text中的文本更新到服務器並將其保存在文本文件中

NSString *post =[[NSString alloc] initWithFormat:@"VIN: %@",vincode.text]; 
     NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding 
           allowLossyConversion:NO]; 
     NSString *postLength = [NSString stringWithFormat:@"%d", [postData 
                    length]]; 
     NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] 
             autorelease]; 
     [request setURL:[NSURL URLWithString:@"Server Detail Here/upload_vin.php"]]; 
     [request setHTTPMethod:@"POST"]; 
     [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
     [request setValue:@"application/x-www-form-urlencoded" 
     forHTTPHeaderField:@"Content-Type"]; 
     [request setHTTPBody:postData]; 
     NSData *urlData = [NSURLConnection sendSynchronousRequest:request 
               returningResponse:nil error:nil]; 
     NSLog(@"Succeeded! Received %d bytes of data",[urlData length]); 
     NSLog(@"VIN is %@",vincode.text); 
     NSString *outputdata = [[NSString alloc] initWithData:urlData 
                encoding:NSASCIIStringEncoding]; 
     NSLog(@"Outputdata is %@",outputdata); 
     NSURLResponse *response; 
     NSError *error; 
     [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
     if(error==nil) 
      NSLog(@"Error is nil"); 
     else 
      NSLog(@"Error is not nil"); 
     NSLog(@"success!"); 
PHP file:::::::::::::: 
    <?php 
    $file = "VinCodes.txt"; 
    #$submitted_vincode = $_GET['VIN'] . " \n"; 
    $submitted_vincode = @$_POST['VIN'] . " \n"; 
    if(!empty($submitted_vincode)){ 
    $Handle = fopen($file, 'a'); 
     fwrite($Handle, $submitted_vincode); 
     print "Vin Code stored in file."; 
     fclose($Handle); 
    }else{ 
     print "Vin code is missing. Try again"; 
    } 
    ?> 
+0

$ filecontents = file_get_contents(「VinCodes.txt」); print $ filecontents;你能否請你添加這段代碼並打印你的文件 – meth

回答

0

辦法不多的代碼,這裏是我做的,(注意:我上傳異步):

NSURL *url = [NSURL URLWithString: @"http://..."]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
[request setHTTPMethod:@"POST"]; 
[request setHTTPBody:data]; 
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
[NSURLConnection sendAsynchronousRequest:request ... 

順便說一句,你確定你想NSASCIIStringEncoding,而不是NSUTF8StringEncoding

如有疑問,我使用Charles網絡代理(免費30天)準確查看發送的內容和響應。

+0

感謝zaph幫助我,但是請你告訴我什麼應該是我的確切代碼實際上我是新的目標c所以這將是非常有用的,如果你告訴主全局代碼部分。我可以用sendAsync嗎?如果是,那麼請你能提供完整的代碼嗎? –

+0

[request setHTTPBody:data]; 沒有這條線?請說明這裏的數據是什麼??(根據我的代碼) –

相關問題