Objective-C 中的 URL 加载系统


URL 加载对于访问 URL(即来自互联网的项目)很有用。它是在以下课程的帮助下提供的 -

  • NSMutableURLRequest
  • NSURL连接
  • NSURL缓存
  • NSURLAuthenticationChallenge
  • NSURL凭证
  • NSURL保护空间
  • NSURL响应
  • NSURL下载
  • NSURL会话

这是一个简单的 url 加载示例。这不能在命令行上运行。我们需要创建 Cocoa 应用程序。

这可以通过在 XCode 中选择 New,然后选择 Project 并在出现的窗口的 OS X 应用程序部分下选择 Cocoa Application 来完成。

单击“下一步”完成一系列步骤,系统将要求您提供项目名称,您可以为其命名。

appdelegate.h 文件如下 -

#import <Cocoa/Cocoa.h>

@interface AppDelegate : NSObject <NSApplicationDelegate>

@property (assign) IBOutlet NSWindow *window;

@end

将 AppDelegate.m 文件更新为以下内容 -

#import "AppDelegate.h"

@interface SampleClass:NSObject<NSURLConnectionDelegate> {
   NSMutableData *_responseData;
}

- (void)initiateURLConnection;
@end

@implementation SampleClass
- (void)initiateURLConnection {
   
   // Create the request.
   NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://date.jsontest.com"]];

   // Create url connection and fire request
   NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
   [conn start];
}

#pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
   // A response has been received, this is where we initialize the instance var you created
   // so that we can append data to it in the didReceiveData method
   // Furthermore, this method is called each time there is a redirect so reinitializing it
   // also serves to clear it
   _responseData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
   // Append the new data to the instance variable you declared
   [_responseData appendData:data];
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
   willCacheResponse:(NSCachedURLResponse*)cachedResponse {
   // Return nil to indicate not necessary to store a cached response for this connection
   return nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
   // The request is complete and data has been received
   // You can parse the stuff in your instance variable now
   NSLog(@"%@",[[NSString alloc]initWithData:_responseData encoding:NSUTF8StringEncoding]);
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
   // The request has failed for some reason!
   // Check the error var
}
@end

@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
   SampleClass *sampleClass = [[SampleClass alloc]init];
   [sampleClass initiateURLConnection];
   // Insert code here to initialize your application
}
@end

现在,当我们编译并运行该程序时,我们将得到以下结果。

2013-09-29 16:50:31.953 NSURLConnectionSample[1444:303] {
   "time": "11:20:31 AM",
   "milliseconds_since_epoch": 1380453631948,
   "date": "09-29-2013"
}

在上面的程序中,我们创建了一个简单的 URL 连接,它以 JSON 格式获取时间并显示时间。

Objective_c_foundation_framework.htm