如何将数据从iOS应用程序发送到http服务器

时间:2013-04-29 08:39:24

标签: php ios xcode

如何从iOS应用程序中的字符串向我的服务器发送一些数据,PHP脚本会将这些数据写入数据库?

5 个答案:

答案 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)

答案 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];
}