我一直致力于将我的 ios 应用程序联网。我需要在我的网站上调用一个 php 文件,然后取回信息。我一直在使用本教程,但它已经过时并且现在不受支持。
http://www.raywenderlich.com/2965/how-to-write-an-ios-app-that-uses-a-web-service
我一直在研究 MKNetworkKit,我认为这是我需要使用的,但我不确定如何实现它。
我一直致力于将我的 ios 应用程序联网。我需要在我的网站上调用一个 php 文件,然后取回信息。我一直在使用本教程,但它已经过时并且现在不受支持。
http://www.raywenderlich.com/2965/how-to-write-an-ios-app-that-uses-a-web-service
我一直在研究 MKNetworkKit,我认为这是我需要使用的,但我不确定如何实现它。
我想大多数人都同意AFNetworking是最适合这个的库。甚至还有关于如何使用它的非常好的raywenderlich.com 教程。
例如,我用这种方式将带有参数的链接的内容 (makemyday.com/web/export.php?id=345) 放入UIWebView
:
- (IBAction)searchForNearbyButtonPressed:(id)sender {
NSURL *baseURL = [NSURL URLWithString:@"http://makemyday.com"];
NSDictionary *parameters = @{@"id": @"345"};
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[client registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[client getPath:@"/web/export.php"
parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"response=%@", [operation.response allHeaderFields]);
[self.webView loadData:responseObject MIMEType:operation.response.MIMEType textEncodingName:operation.response.textEncodingName baseURL:operation.response.URL];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error=%@", error.description);
}
];
}
在帮助中输入“NSURLConnection”。那里有一些很好的例子。
最简单的方法是使用 NSURLConnection 进行同步调用。
在您的服务器响应并关闭之前,这是一个阻塞调用。
NSURL *url = [NSURL URLWithString:@"http://makemyday.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSError *error;
NSURLResponse *response;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
更好的用户体验方法是使用委托异步。我发现以下内容令人满意,因为可以添加 5、10、20、60 秒的时间。
NSURLRequest *theRequest = [NSURLRequest requestWithURL: url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:**20.0**];
NSURLDownload *theDownload = [[NSURLDownload alloc] initWithRequest:theRequest delegate:**self**]; // NOTE THE SELF FOR THE CALLBACks
if (!theDownload) {
//OOPS
}
对失败、成功/完成和文件名使用以下回调方法
- (void)download:(NSURLDownload *)download decideDestinationWithSuggestedFilename:(NSString *)filename;
- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error
- (void)downloadDidFinish:(NSURLDownload *)download;
- (void)download:(NSURLDownload *)download didCreateDestination:(NSString *)path