问题描述
如何使用Objective-C向Web服务发送HTTP请求?我需要从我的MySQL数据库中获取一些数据,所以我需要发送请求以便我可以获取数据。
How to send a HTTP request to a web service using Objective-C ? I need to fetch some data from my MySQL DB, so I need to send the request so I could fetch the data.
推荐答案
编辑,因为这是一个受欢迎的问题,时间在继续。
与此同时,Apple推出了NSJSONSerialization。查看文档:
仅当您需要为早于5.0的iOS创建代码时,您可能需要使用如下所述的json-framwork。
Edit, because this is a popular question and time keeps going on.In the meantime Apple introduced NSJSONSerialization. Have a look a the docs: https://developer.apple.com/documentation/foundation/jsonserializationOnly if you need to create code for iOS earlier than 5.0 you may want to use the json-framwork as mentioned below.
除此之外,以下原始答案仍然有效:
Besides that, the following original answer is still valid:
假设您使用JSON交换数据,你可能有兴趣阅读这篇文章。
Assuming that you exchange your data in JSON, you may be interested in reading this.http://iosdevelopertips.com/cocoa/json-framework-for-iphone-part-2.html
然而,该文章的第一部分回答了关于如何接收数据的更一般性问题来自网络服务器/服务:
However, the first part of that article answers your more general question on how to receive data from a web server/service:
- (NSString *)stringWithUrl:(NSURL *)url
{
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Fetch the JSON response
NSData *urlData;
NSURLResponse *response;
NSError *error;
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
// Construct a String around the Data from the response
return [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
}
这是一个简单的http请求示例,对你的下一个肯定足够好了脚步。
此方法被赋予一个URL,它返回服务器在NSString中发送的数据。
This is a simple example of a http request and surely good enough for your next steps.This method is given a URL and it returns the data sent by the server in an NSString.
一旦工作正常,您会希望避免在请求播出时您的应用程序冻结。
您可以通过异步请求修复它。 Google或stackoverflow上的搜索将为您提供有关该示例和教程的链接。但我建议先从这里开始,尽管这可能不是最终解决方案。
Once that is working properly you will like to avoid that your app freezes while the request is "on the air".You can fix that by asynchronous requests. Google or the search on stackoverflow will provide you with links to examples and tutorials about that. But I suggest to go from here first, although this may not be the final solution.
这篇关于iPhone:如何使用Xcode向Web服务发送HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!