2011-09-28 44 views
2

只是想知道如果我正確地做這個,這似乎是這麼簡單的東西有很多代碼...JSON解析爲GOOGLE API返回圖片iPhone SDK

傳遞與我的鑰匙來此功能的谷歌JSON請求使用ASIHTTPREQUEST

 NSString *url4Google = [[NSString alloc] initWithFormat:@"https://www.googleapis.com/shopping/search/v1/public/products?key=(MY SECRET KEY)&country=GB&q=5035822086234"]; 

     ASIHTTPRequest* request = [self requestWithURL:url4Google]; 

代碼處理...

- (void)requestFinished:(ASIHTTPRequest*)request { 

NSLog(@"GOOGLE SHOPPER IMAGE LOADING"); 

NSDictionary *result = [[request responseString] objectFromJSONString]; 

//GOOGLE SHOPPER IMAGE RETURN.. 

NSArray *Image = [[[[result objectForKey:@"items"] valueForKey:@"product"] valueForKey:@"images"] valueForKey:@"link"] ; 

NSArray *Title = [[[result objectForKey:@"items"] valueForKey:@"product"] valueForKey:@"title"]; 

//NSLog(@"TITLE OF ITEM = %@", Title); 

int size = [Image count]; 
NSLog(@"there are %d product images for this barcode ", size); 

int titlez = [Title count]; 
NSLog(@"there are %d title names for this barcode ", titlez); 

NSArray *imagearray = [Image objectAtIndex:3]; 
NSString *titleofitemis = [Title objectAtIndex:2]; 

//Choosing a number objectAtIndex... 

NSMutableString * result1 = [[NSMutableString alloc] init]; 
for (NSObject * obj in imagearray) 
{ 
    [result1 appendString:[obj description]]; 
} 
NSLog(@"FULL IMAGE URL IS = %@", result1); 

//SET IMAGE 
NSURL* _url = [[NSURL alloc] initWithString:result1]; 
self.url = _url; 
[_url release]; 
[result1 release]; 

NSLog(@"url = %@", url); 

UIImage* image = [ImageManager loadImage:url]; 
if (image) { 
imageView.image = image; 
}  

//SET TITLE 
self.title = titleofitemis; 

NSLog(@"FULL TITLE NAME IS = %@", titleofitemis); 
} 

我使用SBJSON也對的ImageManager異步加載圖像已經位於象後..

我已經做了一些內存管理的對我來說,是不是太在這個例子中的一個問題...

的NSLog輸出

2011-09-28 16:29:17.351 IOSBoilerplate[17906:11c03] done pressed 
2011-09-28 16:29:18.031 IOSBoilerplate[17906:11c03] GOOGLE SHOPPER IMAGE LOADING 
2011-09-28 16:29:18.034 IOSBoilerplate[17906:11c03] there are 25 product images for this  barcode 
2011-09-28 16:29:18.035 IOSBoilerplate[17906:11c03] FULL URL FOR IMAGE = http://static.gam.co/media/films/00/000/0032/32467/image/30403.jpg 

這是最快捷的方式&有這樣做是正確的,我可以稍後做所有錯誤級別檢測..

任何幫助,將不勝感激。

回答

0

你的代碼看起來不錯。一些清理/風格建議:

//... 
NSMutableString *urlString = [NSMutableString string]; // shorter, autoreleased 
for (NSString *s in imagearray) { // already typed 
    [urlString append:s]; 
} 
self.url = [NSURL urlWithString:urlString]; // that's all it takes 
UIImage *displayImage = [ImageManager loadImage:url]; 
// code is very readable, too 

請使用開始以大寫字母實例名稱,如您ImageTitle避免。慣例是大寫的名字用於類,而不是實例。此外,更多描述性名稱(如imageArrayimageList)使代碼更易於理解。

+0

非常感謝您的時間和我的代碼Mundi,我已經是一個一年半的ios開發人員,我一直使用大寫字母,我認爲它現在只是習慣的一部分! – CMM