UIScrollView 中的 JSON 图像

发布于 2025-01-03 15:32:56 字数 1627 浏览 4 评论 0原文

我正在尝试将一些 json 图像放入 UIScrollView 中,但遇到了一个小障碍。 我使用本机 iOS 5 json 解析器 ScrollView 将 JSON 文件解析为 NSDictionary ,

与 NSArray 一起工作正常,如下所示:

    NSArray *immm = [NSArray arrayWithObjects:[UIImage imageNamed:@"cat.png"], [UIImage imageNamed:@"dog1.png"], nil];

 for (int i = 0; i < immm.count; i++) {
    CGRect frame;
    frame.origin.x = self.scrollView.frame.size.width * i;
    frame.origin.y = 0;
    frame.size = self.scrollView.frame.size;

    UIImageView *subview = [[UIImageView alloc] initWithFrame:frame];
    subview.image = [immm objectAtIndex:i];
    [self.scrollView addSubview:subview];
}

并且解析工作正常,它是我编写的 json 文件(正确格式化和验证)并返回此格式的 NSDictionary (被截断,因为长网址,剪切并粘贴了 json 文件的一部分,但它已使用 JSON 验证器进行了正确验证):

{
header =     {
    main =         (
                    {
            img = "http://******.png";
            title = Dog;
        }
  );
};

}

但我在实际 JSON 数据本身上犯了一个错误,我尝试创建循环之前的数组:

 NSMutableDictionary *jsonDict = (NSMutableDictionary*)[NSJSONSerialization JSONObjectWithData:theData options:kNilOptions error:&error];
NSLog(@"%@", jsonDict);

theArray = [[jsonDict objectForKey:@"header"] objectForKey:@"main"];


for (NSDictionary *images in theArray){
    tempArray = [[ NSMutableArray alloc] initWithObjects:[UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString: [jsonDict objectForKey:@"img"]]]], nil];

}

以及其他一些方法,但我刚刚撞到了砖墙,我要么出现空白屏幕,要么崩溃(现在无法重新创建该死的崩溃) 所以我没有正确创建要在 ScrollView 中使用的数组,因为它是 NSLog'ing 5 个空变量,而不是 null 只是空。它打印了适量的内容,JSON 文件中包含 5 个图像,5 个空 (),

干杯

I'm trying to put some json images into a UIScrollView and i'm hitting a minor snag.
Im parsing a JSON file into NSDictionary with the native iOS 5 json parser

ScrollView works fine with an NSArray like:

    NSArray *immm = [NSArray arrayWithObjects:[UIImage imageNamed:@"cat.png"], [UIImage imageNamed:@"dog1.png"], nil];

 for (int i = 0; i < immm.count; i++) {
    CGRect frame;
    frame.origin.x = self.scrollView.frame.size.width * i;
    frame.origin.y = 0;
    frame.size = self.scrollView.frame.size;

    UIImageView *subview = [[UIImageView alloc] initWithFrame:frame];
    subview.image = [immm objectAtIndex:i];
    [self.scrollView addSubview:subview];
}

and the parsing works fine, its a json file I wrote (properly formatted and validated) and returns an NSDictionary in this format (truncated because of long urls, cut and pasted part of the json file but it is properly validated with JSON validator):

{
header =     {
    main =         (
                    {
            img = "http://******.png";
            title = Dog;
        }
  );
};

}

But im making a mistake with the actual JSON data itself, ive tried creating the array before the loop:

 NSMutableDictionary *jsonDict = (NSMutableDictionary*)[NSJSONSerialization JSONObjectWithData:theData options:kNilOptions error:&error];
NSLog(@"%@", jsonDict);

theArray = [[jsonDict objectForKey:@"header"] objectForKey:@"main"];


for (NSDictionary *images in theArray){
    tempArray = [[ NSMutableArray alloc] initWithObjects:[UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString: [jsonDict objectForKey:@"img"]]]], nil];

}

and a few other ways but I've just hit a brick wall, I'm either getting a blank screen or a crash (cant recreate the damn crash now)
So im not creating the array to be used in the ScrollView properly as it's NSLog'ing 5 empty variables, not null just empty. Its printing the right amount of nothing tho, 5 images in the JSON file, 5 empty (),

Cheers

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

落墨 2025-01-10 15:32:56

您可以使用 valueForKeyPath: 方法一次性获取 JSON 中多个级别的对象,如下所示:

NSArray *imageURLs = [jsonDict valueForKeyPath:@"header.main.img"];

valueForKeyPath 方法很聪明,因为如果它遇到数组,它会自动将路径中的下一位应用于该数组中的每个项目,这就是我们如何在一行中获取主数组中每个对象内的所有 img 元素。

要将其转换为图像数组,请执行以下操作:

NSMutableArray *tempArray = [NSMutableArray array];
for (NSString *imageURL in imageURLs)
{
    NSURL *URL = [NSURL URLWithString:imageURL];
    NSData *data = [NSData dataWithContentsOfURL:URL];
    UIImage *image = [UIImage imageWithData:data];
    [tempArray addObject:image];
}

注意:这将需要很长时间才能执行,因为 [NSData dataWithContentsOfURL:URL] 可能需要几秒钟的时间来下载每个 URL。您应该在后台线程上运行它,或者使用 NSURLConnection 来进行下载。

或者,您可能需要考虑使用异步图像下载库,例如这个。这将允许您通过 URL 将图像分配给界面中的 UIImageViews,并且它将在后台下载它们,而不会阻塞您的界面。

示例:

AsyncImageView *myImageView = [[AsyncImageView alloc] initWithFrame:CGRect(0,0,100,100)];
myImageView.imageURL = [NSURL URLWithString:SOME_STRING_FROM_THE_imageURLs_ARRAY];

这将自动加载图像,在加载时在图像视图中显示一个旋转器,然后在加载后淡入图像。如果您想再次显示它,它将被缓存以供下次使用。

You can use the valueForKeyPath: method to grab objects several levels deep in your JSON in one go like this:

NSArray *imageURLs = [jsonDict valueForKeyPath:@"header.main.img"];

The valueForKeyPath method is clever because if it encounters an array it will automatically apply the next bit in the path to every item in that array, which is how we can grab all the img elements inside every object in the main array in one line.

To convert this to an array of images, do the following:

NSMutableArray *tempArray = [NSMutableArray array];
for (NSString *imageURL in imageURLs)
{
    NSURL *URL = [NSURL URLWithString:imageURL];
    NSData *data = [NSData dataWithContentsOfURL:URL];
    UIImage *image = [UIImage imageWithData:data];
    [tempArray addObject:image];
}

Note: This will take a long time to execute because [NSData dataWithContentsOfURL:URL] may take several seconds to download each URL. You should either run this on a background thread, or use NSURLConnection to do the downloading.

Alternatively, you may want to consider using an asynchronous image downloading library like this one. That will let you assign images to UIImageViews in your interface by URL, and it will download them in the background without blocking your interface.

Example:

AsyncImageView *myImageView = [[AsyncImageView alloc] initWithFrame:CGRect(0,0,100,100)];
myImageView.imageURL = [NSURL URLWithString:SOME_STRING_FROM_THE_imageURLs_ARRAY];

This would then load the image automatically, showing a spinner in the imageview while it loads and then fading in the image when it has loaded. It would then be cached for next time if you want to display it again.

帝王念 2025-01-10 15:32:56
for (NSDictionary *images in theArray)
{
    theArray = ...;
}

首先,您正在循环遍历您之后正在编辑的同一个数组,但这可能只是您帖子中的一个拼写错误。

您确定正在访问 JSON 字典中的正确对象吗?
看起来更像

[[jsonArray objectForKey:@"main"] objectForKey:@"img"]

什么。

for (NSDictionary *images in theArray)
{
    theArray = ...;
}

First off you are looping through the same Array you're editing right after, but thats probably just a typo in your post.

Are you sure you're accessing the right objects in your JSON Dictionary?
Seems more like

[[jsonArray objectForKey:@"main"] objectForKey:@"img"]

or something.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文