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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16274450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 03:17:58  来源:igfitidea点击:

How to send data from iOS app to http server

phpiosxcode

提问by stepik21

How can I send some data from a string in a iOS app to my server, where a PHP script will write this data to a database?

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

回答by stepik21

so finaly, I have one code, which works!

所以最后,我有一个代码,它有效!

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

回答by Divyam shukla

By converting this string in UTF8Encoding you can send it.

通过在 UTF8Encoding 中转换此字符串,您可以发送它。

回答by Praveen kalal

Try this code

试试这个代码

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

回答by Mannam Brahmam

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