我一直在研究如何将数据从mysql服务器加载到我的ios设备。我见过的大多数示例都将变量发送到服务器(如用户名和密码),然后使用POST检索所需的信息。就我而言,我不需要向服务器发送任何信息,只需检索。
所以我的问题是,我是否需要使用POST来获取信息?
另外,我似乎无法在php部分找到任何示例。我应该如何编码我的php文件以从数据库中的表中返回所有信息?对不起,这可能听起来像一个模糊的问题,但我似乎无法找到任何例子。
非常感谢能够提供帮助的任何人!
答案 0 :(得分:1)
您可以使用以下内容:
- (void)viewDidLoad
{
[super viewDidLoad];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSURL *url = [NSURL URLWithString:__YOUR URL__];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (connection) {
self.rssData = [NSMutableData data];
} else {
NSLog(@"Connection failed");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[self.rssData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.rssData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
NSString *result = [[NSString alloc] initWithData:self.rssData encoding:NSUTF8StringEncoding];
NSLog(@"%@",result);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"%@", error);
}
希望有所帮助!
答案 1 :(得分:1)
您还可以使用 GET 来检索数据。
举个例子:
在.h
@interface WSHandler : NSObject <NSURLConnectionDelegate>
{
NSMutableData *receivedData;
}
- (void)callWebService;
@end
in .m:
- (void)callWebService
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:WS_URL]];
[request setHTTPMethod:@"GET"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection)
{
receivedData = nil;
}
else
{
DLog(@"Connection could not be established");
}
}
#pragma mark - NSURLConnection delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
if (!receivedData)
receivedData = [[NSMutableData alloc] initWithData:data];
else
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
DLog(@"***** Connection failed");
receivedData=nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// do something with the data
DLog(@"***** Succeeded! Received %d bytes of data",[receivedData length]);
DLog(@"***** AS UTF8:%@",[[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]);
}