简体   繁体   English

从URL获取图像到objective-c中的数组

[英]get images from URL into an array in objective-c

I am wanting to get an array of all the urls to images from a page. 我想从页面获取图像的所有URL的数组。

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

What I have done here, is to get a page ( www.foo.com/urls.html ) full of all the image urls from http://foo.com/bar.html through javascript which looks like this: 我在这里所做的是通过一个如下所示的javascript获取一个页面( www.foo.com/urls.html ),其中包含来自http://foo.com/bar.html的所有图像URL:

HTML: 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>
...

I want to then be able to create an array of all the urls in objective c would that be possible? 然后,我希望能够在目标c中创建所有URL的数组,这可能吗?

is there a better way to do it than this? 有没有比这更好的方法了?

You should store the images url into your database. 您应该将图像URL存储到数据库中。

Write a script to get those images and put then into a json array 编写脚本以获取这些图像,然后将其放入json数组

PHP 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);
?>

Then from your iOS app make a request the JSON data PHP script. 然后从您的iOS应用程序请求JSON数据PHP脚本。

JSON: 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"
    ]
}

Finally in your app store it into an array. 最后,在您的应用中将其存储到一个数组中。

IOS 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);

While I'm not 100% certain I understand your issue and what you're trying to accomplish, it sounds to me like you're trying to: 虽然我不是100%地确定我了解您的问题以及您要完成的工作,但对我来说,这听起来像是您在尝试:

  1. Run your JS code and have your URLs print out in an HTML page 运行您的JS代码,并在HTML页面中打印出您的URL
  2. At the same time you're generating your HTML page's list of URLs, you want to collect those same URLs in an array for use within and iOS project. 在生成HTML页面的URL列表的同时,您希望将这些相同的URL收集到数组中以供iOS项目中使用。

This can be done with the new JavaScriptCore framework in iOS. 这可以通过iOS中的新JavaScriptCore框架来完成。 I must say that the inspiration for this answer I owe whole-heartedly to the excellent chapter on JavaScriptCore by Pietro Rea in iOS 7 by Tutorials from RayWenderlich.com . 我必须说,这个答案的灵感来自于RayWenderlich.com的Tutorials在iOS 7中Pietro Rea 撰写的关于JavaScriptCore的出色章节。 It's an absolute must read for this type of stuff. 这是绝对必读的东西。

To arrive at your solution (for our purposes, I'll assume your array is being manipulated within an iOS view controller), you'll need to refactor your JavaScript file's code a bit so that you can build your Objective-C array at the same time you build your HTML page. 为了提供您的解决方案(出于我们的目的,我假设您的数组在iOS视图控制器中进行操作),您需要稍微重构JavaScript文件的代码,以便您可以在同时构建HTML页面。 Also, instead of creating the HTML page when your js/html files have loaded, I would allow my iOS view controller to control when this occurs. 此外,我将允许我的iOS视图控制器控制何时发生这种情况,而不是在加载js / html文件时创建HTML页面。

MyJavascriptFile.js: (Ensure you include this file in the Copy Bundle Resources section of your iOS Project 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>

Now, in our iOS Project: 现在,在我们的iOS项目中:

Header file: 头文件:

//  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

Implementation file: 实施文件:

//  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

Don't forget to import the JavaScriptCore framework into your iOS project! 不要忘记将JavaScriptCore框架导入到您的iOS项目中! While I'm unable to test this solution at present, it should certainly be enough to get you started. 虽然我目前无法测试此解决方案,但肯定足以让您入门。 Again, I can't stress enough how awesome the raywenderlich.com tutorial is on this subject so check it out for the full explanation of everything here. 再次强调一下, raywenderlich.com教程在这个主题上有多出色,因此请查看此处的所有内容的完整说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM