Ray's playground

 

Web Service(Chapter 28 of Cocoa Programming for Mac OS X)

 1 #import "AppController.h"
 2 #define AWS_ID @"1CKE6MZ6S27EFQ458402"
 3 
 4 @implementation AppController
 5 
 6 - (id)init
 7 {
 8     self = [super init];
 9     if (self) {
10         // Initialization code here.
11     }
12     
13     return self;
14 }
15 
16 - (IBAction)fetchBooks:(id)sender
17 {
18     [progress startAnimation:nil];
19     
20     NSString *input = [searchField stringValue];
21     NSString *searchString = [input stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
22     NSLog(@"searchString = %@", searchString);
23     
24     NSString *urlString = [NSString stringWithFormat:
25                                                     @"http://ecs.amazonaws.com/onca/xml?"
26                                                     @"Service=AWSECommerceService&"
27                                                     @"AWSAcccessKeyID=%@&"
28                                                     @"Operation=ItemSearch&"
29                                                     @"SearchIndex=Books&"
30                                                     @"Keywords=%@&"
31                                                     @"Version=20007-07-16", AWS_ID, searchString];
32     NSURL *url = [NSURL URLWithString:urlString];
33     NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30];
34     
35     NSData *urlData;
36     NSURLResponse *response;
37     NSError *error;
38     urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
39     
40     if(!urlData)
41     {
42         NSAlert *alert = [NSAlert alertWithError:error];
43         [alert runModal];
44         return;
45     }
46     
47     [doc release];
48     doc = [[NSXMLDocument alloc] initWithData:urlData options:0 error:&error];
49     NSLog(@"doc = %@", doc);
50     if (!doc) 
51     {
52         NSAlert *alert = [NSAlert alertWithError:error];
53         [alert runModal];
54         return;
55     }
56     
57     [itemNodes release];
58     itemNodes = [[doc nodesForXPath:@"ItemSearchResponse/Items/Item" error:&error] retain];
59     if (!itemNodes) 
60     {
61         NSAlert *alert = [NSAlert alertWithError:error];
62         [alert runModal];
63         return;
64     }
65     
66     [tableView reloadData];
67     [progress stopAnimation:nil];
68 }
69 
70 - (int)numberOfRowsInTableView:(NSTableView*)tv
71 {
72     return 0;
73 }
74 
75 - (void)dealloc
76 {
77     [super dealloc];
78 }
79 
80 @end

posted on 2011-03-22 15:06  Ray Z  阅读(328)  评论(0编辑  收藏  举报

导航