Objective-C URL載入系統

2019-10-16 23:14:56

URL載入在存取URL(即來自網際網路的專案)時很有用。 它是在以下類別的幫助下提供的 -

  • NSMutableURLRequest
  • NSURLConnection
  • NSURLCache
  • NSURLAuthenticationChallenge
  • NSURLCredential
  • NSURLProtectionSpace
  • NSURLResponse
  • NSURLDownload
  • NSURLSession

下面是一個簡單的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

現在,當編譯並執行程式時,將得到以下結果。

2018-09-29 06:50:31.953 NSURLConnectionSample[1444:303] {
   "time": "06:21:51 AM",
   "milliseconds_since_epoch": 1570453631948,
   "date": "09-29-2018"
}

在上面的程式中,建立了一個簡單的URL連線,它以JSON格式返回並顯示時間。