如何在Objective-C中使用URL Xcode 8.1在我的PHP服务器中发送数据

我想从Xcode发送NSString数据到我的PHP服务器,在这个例子中使用url: http : //11.1.12.173 : 1000

我需要XCODE 8.1的解决scheme,因为有些代码在最新的Xcode中不起作用。

NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://11.1.12.173:1000"]]; [req setHTTPMethod:@"POST"]; NSData *postData = [deviceToken dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]]; [req addValue:postLength forHTTPHeaderField:@"Content-Length"]; [req setHTTPBody:postData]; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *task = [session dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { // Do something with response data here - convert to JSON, check if error exists, etc.... }]; [task resume]; 

我试过这个代码,但它不工作。

这是一个同步解决scheme,但它可能会为你工作。 只要在不同的队列中使用它,即使连接速度太慢,也不会有问题。 这是我做什么来执行POST请求:

 -(NSString*)launchURL:(NSURL*)url withPostString:(NSString*)post { NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:url]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setHTTPBody:postData]; NSError *error = nil; NSHTTPURLResponse *response = nil; NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; if (response.statusCode >= 200 && response.statusCode < 300) { NSString *responseData = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding]; if (responseData.length > 0) return responseData; } else if (error) return [error description]; return nil; } 

该string需要有正确的编码(百分比编码)才能工作,为了做到这一点,我将该函数添加到NSString(该方法始终工作,即使在非常老版本的macOS上):

 @implementation NSString (WebString) -(NSString*)stringToWebStructure { NSString* webString = [self stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; webString = [webString stringByReplacingOccurrencesOfString:@"&" withString:@"%26"]; webString = [webString stringByReplacingOccurrencesOfString:@"?" withString:@"%3F"]; return webString; } @end 

您只需将两者添加到将要发出请求的同一个文件中,并以此方式使用它:

 [self launchURL:[NSURL URLWithString:@"http://11.1.12.173:1000"] withPostString:[deviceToken stringToWebStructure]]; 

证实在Xcode 8中工作。