我正在编写一个扫描条形码的应用程序,然后查询Outpan.com以获取条形码编号的信息。 如何从网址请求中提取信息? 下面是扫描成功后的输出示例。 我怎么能将名称存储到NSString中?
这是我用来访问信息的代码。
- (void) sendRequest {
NSString *myString = @"https://api.outpan.com/v2/products/";
NSString *secondhalf= _barcode;
NSString *thirdHalf = @"?apikey=935b8b8e102f93220b751a4e1c66126a";
NSString *test = [myString stringByAppendingString:secondhalf];
NSString *text = [test stringByAppendingString:thirdHalf];
if (![text isEqualToString:@""]) {
NSURL *url = [NSURL URLWithString:text];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
}
}
通常我会尝试使用类似
的内容 NSString* value = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('myId').value"];
如果html看起来像这样
<html>
<body>
<input id="myId" type="text" value="TextValue"/>
</body>
</html>
但是html就像这样
<html><head></head><body><pre style="word-wrap: break-word; white-space: pre- wrap;">{
"gtin": "0014633156720",
"outpan_url": "https:\/\/www.outpan.com\/view_product.php? barcode=0014633156720",
"name": "Battlefield: Bad Company 2",
"attributes": {
"Distribution Media\/Method": "Blu-ray Disc",
"ESRB Rating": "RP (Rating Pending)",
"Manufacturer": "Electronic Arts",
"Manufacturer Part Number": "15672",
"Platform": "PlayStation 3",
"Platform Supported": "PlayStation 3",
"Software Main Type": "Game",
"Software Sub Type": "First Person Shooter"
},
"images": [],
"videos": [],
"categories": []
}</pre></body></html>
答案 0 :(得分:5)
问题是您正在尝试使用UIWebView发出api请求。 api可能会将您的Accepts标头视为text / html,因此会在网页中向您发送api响应,而不仅仅是原始JSON。请尝试使用NSURLSession发出请求。
responseBody
未经测试,因为我没有真正的条形码,但您应该在cbind
词典中看到您要求的JSON。