![](/img/trans.png)
[英]Sending Data to Server Using Multiple View Controllers in ObjectiveC
[英]Sending Data to Server in ObjectiveC
我目前正在嘗試將數據從我的xcode項目發送到我制作的服務器上,但是當我運行應用程序時,數據似乎沒有出現在表中。
這非常簡單,允許用戶輸入名稱和按下按鈕時發送的消息。 我不知道我做錯了什么,有什么建議嗎?
這是我的PHP代碼:
<?php
$username = "root";
$database = "testdb";
mysql_connect('localhost', $username);
@mysql_select_db($database) or die ("Unable to find database");
$name = @$_GET["name"];
$message = @$_GET["message"];
$query = "INSERT INTO test VALUES ('', '$name', '$message')";
mysql_query($query) or die (mysql_error("error"));
mysql_close();
?>
和我的obj c代碼:
。H
#import <UIKit/UIKit.h>
#define kPostURL @"http://localhost/TESTCONNECT.php" //variable to use whenever
#define kName @"name"
#define kMessage @"message"
@interface FirstViewController : UIViewController{
IBOutlet UITextField *nameText;
IBOutlet UITextView *messageText;
NSURLConnection *postConnection;
}
-(IBAction)post:(id)sender;
@end
.m
#import "FirstViewController.h"
@interface FirstViewController ()
@end
@implementation FirstViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
-(void) postMessage:(NSString*) message withName:(NSString *) name{
if(name !=nil && message !=nil){
NSMutableString *postString = [NSMutableString stringWithString:kPostURL];
[postString appendString:[NSString stringWithFormat:@"?%@=%@", kName, name]];
[postString appendString: [NSString stringWithFormat:@"&%@=%@", kMessage, message]];
[postString setString:[postString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request =[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString: postString]];
[request setHTTPMethod:@"POST"];
postConnection =[[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
}
}
-(IBAction)post:(id)sender{
[self postMessage:messageText.text withName:nameText.text];
[messageText resignFirstResponder];
messageText.text=nil;
nameText.text=nil;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
您正在用C語言編寫一個帖子,因此在PHP中,您需要使用$ _POST而不是$ _GET捕獲變量。
這是您實際將字符串發送到php(POST)文件的方式。 我認為其余的應該起作用。 我沒有嘗試過,但對我來說看起來不錯。
- (void) send {
NSString *testString = @"this is a test";
NSString *post =[NSString stringWithFormat:@"message=%@",testString];
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:@"YOUR/URL/test.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.