将URL中的图像转换为objective-c中的数组

时间:2014-05-06 13:10:43

标签: javascript ios objective-c arrays

我想从页面获取图像的所有网址数组。

使用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>

我在这里做的是获取一个页面( www.foo.com/urls.html ),其中包含来自 http://foo.com/bar.html 通过javascript看起来像这样:

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中创建所有网址的数组吗?

有没有比这更好的方法?

2 个答案:

答案 0 :(得分:1)

您应该将图片网址存储到您的数据库中。

编写一个脚本来获取这些图像然后放入一个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);

答案 1 :(得分:0)

虽然我不是100%肯定我理解你的问题以及你想要完成的事情,但听起来对我来说就像你想要的那样:

  1. 运行您的JS代码,并在HTML页面中打印您的URL
  2. 在您生成HTML页面的URL列表的同时,您希望在数组中收集相同的URL以便在iOS项目中使用。
  3. 这可以使用iOS中的新JavaScriptCore框架来完成。我必须说这个答案的灵感我全心全意地归功于来自RayWenderlich.com的Tutorials的iOS 7中Pietro Rea关于JavaScriptCore的精彩篇章。对于这种类型的东西,绝对必须阅读。

    为了达到你的解决方案(为了我们的目的,我假设你的数组在iOS视图控制器中被操作),你需要稍微重构你的JavaScript文件的代码,这样你就可以构建你的Objective-C在构建HTML页面的同时使用数组。此外,当你的js / html文件加载时,我不允许创建HTML页面,而是允许我的iOS视图控制器控制何时发生这种情况。

    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教程在这个主题上有多棒,所以请在这里查看完整的解释。