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

问题描述:

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

+0

是喜是它为你工作? – 2013-04-29 08:52:59

所以finaly,我有一个代码,它的作品!

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]; 
+2

这将只是请求,而不是urlRequest – Javier 2013-08-22 00:02:37

+0

什么是PHP代码? – 2014-10-26 20:25:39

试试这个代码

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"]; 

通过UTF8Encoding,你可以把它这个字符串转换。

[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]; 
} 
+0

此代码支持iOS9 – 2015-12-08 07:40:28