[英]get images from URL into an array in objective-c
我想從頁面獲取圖像的所有URL的數組。
使用Javascript:
<script>
function newEl(tag){return document.createElement(tag);}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
myAjaxRequest("http://foo.com/bar.html", onHtmlLoaded);
}
function onHtmlLoaded(ajax)
{
var div = newEl('div');
div.innerHTML = ajax.responseText;
var imgs = div.getElementsByTagName('img');
for (var i=7;i<imgs.length;i++)
{
document.write("<p id='"+i+"'>"+imgs[i].src+"<p/>");
}
}
function myAjaxRequest(url, callback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
callback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
}
ajax.open("GET", url, true);
ajax.send();
}
</script>
我在這里所做的是通過一個如下所示的javascript獲取一個頁面( www.foo.com/urls.html ),其中包含來自http://foo.com/bar.html的所有圖像URL:
HTML:
<p id="1">http://www.foo.com/x.jpg</p>
<p id="2">http://www.foo.com/y.jpg</p>
<p id="3">http://www.foo.com/z.jpg</p>
...
然后,我希望能夠在目標c中創建所有URL的數組,這可能嗎?
有沒有比這更好的方法了?
您應該將圖像URL存儲到數據庫中。
編寫腳本以獲取這些圖像,然后將其放入json數組
PHP
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") ";
}
$res = $mysqli->query("SELECT image_name FROM images");
$data=array();
while ($row = $res->fetch_assoc()) {
$data['images'][] = $row['image_name'];
}
echo json_encode($data);
?>
然后從您的iOS
應用程序請求JSON
數據PHP
腳本。
JSON:
{
"images": [
"http: //xxxxxxxxx.co.uk/video%20images/ONYX%20sofa.jpg",
"http: //xxxxxxxxx.co.uk/video%20images/aaron%20duran.jpg",
"http: //xxxxxxxxx.co.uk/video%20images/littledragon.jpg",
"http: //xxxxxxxxx.co.uk/video%20images/cantalivering%20house.jpg"
]
}
最后,在您的應用中將其存儲到一個數組中。
IOS
NSURL *url = [NSURL URLWithString:@"http://www.url.com/get_images.php"];
//Creating the data object that will hold the content of the URL
NSData *jsonData = [NSData dataWithContentsOfURL:url];
NSError *error = nil;
//parse the JSON
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers error:&error];
//Here is the array
NSArray *images = result[@"images"];
NSLog("images =%@", images);
雖然我不是100%地確定我了解您的問題以及您要完成的工作,但對我來說,這聽起來像是您在嘗試:
這可以通過iOS中的新JavaScriptCore框架來完成。 我必須說,這個答案的靈感來自於RayWenderlich.com的Tutorials在iOS 7中Pietro Rea 撰寫的關於JavaScriptCore的出色章節。 這是絕對必讀的東西。
為了提供您的解決方案(出於我們的目的,我假設您的數組在iOS視圖控制器中進行操作),您需要稍微重構JavaScript文件的代碼,以便您可以在同時構建HTML頁面。 此外,我將允許我的iOS視圖控制器控制何時發生這種情況,而不是在加載js / html文件時創建HTML頁面。
MyJavascriptFile.js :(確保將此文件包含在iOS項目的“副本捆綁資源”部分中
<script>
function newEl(tag){return document.createElement(tag);}
//replace previous on load function call with function
//that is called from Objective-C
function onObjectiveCLoaded() {
myAjaxRequest("http://foo.com/bar.html", onHtmlLoaded);
}
function onHtmlLoaded(ajax) {
var div = newEl('div');
div.innerHTML = ajax.responseText;
var imgs = div.getElementsByTagName('img');
for (var i=7;i<imgs.length;i++) {
document.write("<p id='"+i+"'>"+imgs[i].src+"<p/>");
//also, add our url to our objective-c array at same time
//this function is defined in MyViewController.m iOS file
addURLToObjectiveCArray(imgs[i].src);
}
}
function myAjaxRequest(url, callback) {
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (this.readyState==4 && this.status==200)
callback(this);
}
ajax.onerror = function() {
console.log("AJAX request failed to: " + url);
}
ajax.open("GET", url, true);
ajax.send();
}
</script>
現在,在我們的iOS項目中:
頭文件:
// MyViewController.h
#import <UIKit/UIKit.h>
#import <JavaScriptCore/JavaScriptCore.h>
@interface MyViewController : UIViewController
//this is required execution environment to run JS code locally
@property (strong, nonatomic) JSContext *jsContext;
@end
實施文件:
// MyViewController.m
#import "MyViewController.h"
@interface MyViewController ()
@property (strong, nonatomic) NSMutableArray *myArrayOfURLs;
@end
@implementation MyViewController
- (void)viewDidLoad {
[super viewDidLoad];
//init our array
self.myArrayOfURLs = [NSMutableArray new];
//get a path to the javascript file we included in our bundle
NSString *javascriptPath = [[NSBundle mainBundle] pathForResource:@"MyJavascriptFileName" ofType:@"js"];
//turn our entire JS file into single string which we'll execute in our JS context
NSError *error = nil;
NSString *javascriptString = [NSString stringWithContentsOfFile:javascriptPath encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(@"Oops. Something happened.");
return;
}
//init our context and evaluate our string of javascript
self.jsContext = [[JSContext alloc] init];
[self.jsContext evaluateScript:javascriptString];
//grab a weak reference to self so we don't create strong retain cycle
//within the block callback we're about to create
__weak MyViewController *wSelf = self;
//define the method/function we're calling from our JS file to add url to array
//as we're creating our HTML page in our JS file, our JS file will call this
//addURLToObjectiveCArray callback, passing in the current URL so we can add it
self.jsContext[@"addURLToObjectiveCArray"] = ^(NSString *url) {
[wSelf.myArrayOfURLs addObject:url];
};
//to ensure we don't prematurely create our url list in the JS file only,
//only call that part of your JS file code from a function call here via
//our context
JSValue *jsFunction = self.jsContext[@"onObjectiveCLoaded"];
[jsFunction callWithArguments:@[]];
}
@end
不要忘記將JavaScriptCore框架導入到您的iOS項目中! 雖然我目前無法測試此解決方案,但肯定足以讓您入門。 再次強調一下, raywenderlich.com教程在這個主題上有多出色,因此請查看此處的所有內容的完整說明。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.