如何从iOS应用程序中的字符串向我的服务器发送一些数据,PHP脚本会将这些数据写入数据库?
答案 0 :(得分:10)
最后,我有一个代码,它有效!
NSString *content = @"field1=42&field2=Hello";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.example.com/form.php"]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[content dataUsingEncoding:NSUTF8StringEncoding]];
// generates an autoreleased NSURLConnection
[NSURLConnection connectionWithRequest:request delegate:self];
答案 1 :(得分:1)
通过在UTF8Encoding中转换此字符串,您可以发送它。
答案 2 :(得分:0)
试试此代码
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody: jsonData];
[request setValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"];
答案 3 :(得分:0)
看一下NSURLConnection的Apple教程:
答案 4 :(得分:0)
[self deviceCheck:@"123" Completetion:^(NSArray *result, NSError *error) {
//Here use result,and check the error
}];
//Method
-(void)deviceCheck:(NSString *)device Completetion:(void (^) (NSArray * result,NSError * error))completion{
NSString *deviceRequestString = [NSString stringWithFormat:@"%@?device=%@",webservice,device];
NSURL *JSONURL = [NSURL URLWithString:deviceRequestString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:JSONURL];
NSURLSessionDataTask * dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request
completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if(data == nil){
completion(nil,error);
return;
}
NSError *myError;
NSArray *tableArray = [[NSArray alloc]initWithArray:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&myError]];
completion(tableArray,myError);
}];
[dataTask resume];
}