我一直在研究如何将数据从 mysql 服务器加载到我的 ios 设备。我见过的大多数示例都向服务器发送变量(如用户名和密码),然后使用 POST 检索所需的信息。就我而言,我不需要向服务器发送任何信息,只需检索即可。
所以我的问题是,我需要使用 POST 来获取信息吗?
另外,我似乎在 php 部分找不到任何示例。我应该如何编码我的 php 文件以从我的数据库中的表中返回所有信息?抱歉,这听起来像是一个模糊的问题,但我似乎找不到任何例子。
非常感谢任何可以提供帮助的人!
你可以使用这样的东西:
- (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);
}
希望对您有所帮助!
您还可以使用GET检索数据。
举个例子:
在.h
@interface WSHandler : NSObject <NSURLConnectionDelegate>
{
NSMutableData *receivedData;
}
- (void)callWebService;
@end
以 .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]);
}