1

我已经在这个网站上看到了几乎所有关于 NSURL 的帖子,但我仍然卡住了。我正在使用 Xcode 4.5。

我正在尝试下载图像并将它们显示在 UIScrollView 中。

我想使用 URL 异步下载图像,这些图像存储在使用 JSON 填充的数组中。我从数据库中的 JSON 抓取中获取 URL。这工作得很好,我可以看到 URL 被放置到 urlArray 中,但是使 URLConnection 获取图像似乎失败了。

我无法下载任何图像,或者至少它们没有出现在我的 imageArray 中。

这是我的代码,感谢您的帮助!!让我知道还需要什么

- (void)viewDidLoad
{
    [super viewDidLoad];
    //show network activity to user.... very useful
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    //call getJSON. getJSON does not parse, but it connects and gets the data.
    [self getJSON];



}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)getJSON
{
    NSURL *url = [NSURL URLWithString:@"http://"My server goes here/json.php"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //just initialize the connection, do not 
    [[NSURLConnection alloc] initWithRequest:request delegate:self]; //"Ecression result unused" warning here
}

- (void)getNextImage
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    for (int y = 0; y < urlArray.count; y++)
    {
    NSString *urlString = [urlArray objectAtIndex:y];
    NSLog(@"Array String is: %@ ", urlString);
    NSURL *arrayURL = [NSURL URLWithString:urlString];
    NSURLRequest *imageRequest = [NSURLRequest requestWithURL:arrayURL];
    NSData *imgData = [[NSURLConnection alloc] initWithRequest:imageRequest delegate:self]; //"Incompatible pointer types initializing ..." warning here
    imageData = [UIImage imageWithData:imgData];
    [imageArray addObject:imageData];

    }
    NSLog(@"LEAVING getNextImage");
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    theJsonData = [[NSMutableData alloc] init];
}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [theJsonData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    urlArray = [[NSMutableArray alloc] init];
    //This is where all the JSON Parsing is being done.
    //Turn off the data indicator, because the download is complete.
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

    jsonArray = [NSJSONSerialization JSONObjectWithData:theJsonData options:nil error:nil];   //"Incompatible pointer types initializing ..." warning here

    //get the URL strings out of the jsonArray
    for (int x = 0; x < jsonArray.count; x++)
    {
        NSString *urlString = [[jsonArray objectAtIndex:x] objectForKey:@"image_URL"];
        NSLog(@"String is %@ ", urlString);
        [urlArray addObject:urlString];
    }
    [self getNextImage];

    //display the images..... Not sure why this is in connectionDidFinishLoading.
    for (int x = 0; x < imageArray.count; x++)
    {
        CGRect frame;
        frame.origin.x = self.mainScroll.frame.size.width * x;
        frame.origin.y = 0;
        frame.size = self.mainScroll.frame.size;

        UIImageView *nextIV = [[UIImageView alloc] initWithFrame:frame];
        [nextIV setImage:imageData];

        [self.mainScroll addSubview:nextIV];
        //NSLog(@"Pass %d", x);
    }

    self.mainScroll.contentSize = CGSizeMake(self.mainScroll.frame.size.width * imageArray.count,1.0);

    NSLog(@"!!!!!!leaving connection did finnish loading!!!!!");

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    //show error message to user if there is a connection error.
    UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"The Download could not complete - please make sure you're connected to the internet." delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
    [errorView show];
    //turn off the network activity indicatior
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
4

1 回答 1

3

你永远不会下载 imageData。您为其分配请求对象。这就是为什么你也会收到警告。NSURLConnection 对象不是 NSData 对象:NSData *imgData = [[NSURLConnection alloc] initWithRequest:imageRequest delegate:self]; //"Incompatible pointer types initializing ..." warning here

我今天将使用 startAsyncConnection 方法重写它。秒

- 你去吧,未经测试并用文本编辑编写,但它应该让你开始(我重用了你的大部分代码,但也减少了很多)

#import "RootViewController.h"

@interface RootViewController ()
@property(assign) IBOutlet UIScrollView *mainScroll;
@end

@implementation RootViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [self getJSONAndImageData];
}

- (void)getJSONAndImageData
{
    NSURL *url = [NSURL URLWithString:@"http://My server goes here/json.php"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse*r, NSData*d, NSError*e) {
        [self parseJSONAndGetImages:d];
    }];
}

- (void)parseJSONAndGetImages:(NSData*)data
{
    NSMutableArray *urlArray = [[NSMutableArray alloc] init];
    //This is where all the JSON Parsing is being done.
    //Turn off the data indicator, because the download is complete.
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

    NSArray *jsonArray = (NSArray*)[NSJSONSerialization JSONObjectWithData:data options:nil error:nil];   //"Incompatible pointer types initializing ..." warning here => likely not an array then
    assert([jsonArray isKindOfClass:[NSArray class]]);

    //could be made in one liner with KVC
    //get the URL strings out of the jsonArray
    for (int x = 0; x < jsonArray.count; x++)
    {
        NSString *urlString = [[jsonArray objectAtIndex:x] objectForKey:@"image_URL"];
        NSLog(@"String is %@ ", urlString);
        [urlArray addObject:urlString];
    }

    [self loadImageArray:urlArray handler:^(NSArray* imageArray) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        for (int x = 0; x < imageArray.count; x++)
        {
            CGRect frame;
            frame.origin.x = self.mainScroll.frame.size.width * x;
            frame.origin.y = 0;
            frame.size = self.mainScroll.frame.size;

            UIImageView *nextIV = [[UIImageView alloc] initWithFrame:frame];
            [nextIV setImage:imageArray[x]];

            [self.mainScroll addSubview:nextIV];
            //NSLog(@"Pass %d", x);
        }

        self.mainScroll.contentSize = CGSizeMake(self.mainScroll.frame.size.width * imageArray.count,1.0);
    }];
}

//for SIMPLICITY I do synchronous networking here!
- (void)loadImageArray:(NSArray *)urlArray handler:(void(^)())handler {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableArray *imageArray = [NSMutableArray array];
        for (int y = 0; y < urlArray.count; y++)
        {
            NSString *urlString = [urlArray objectAtIndex:y];
            NSLog(@"Array String is: %@ ", urlString);
            NSURL *arrayURL = [NSURL URLWithString:urlString];
            NSURLRequest *imageRequest = [NSURLRequest requestWithURL:arrayURL];
            NSData *imgData = [NSURLConnection sendSynchronousRequest:imageRequest returningResponse:nil error:nil];
            UIImage *image = [UIImage imageWithData:imgData];
            [imageArray addObject:image];
        }

        dispatch_async(dispatch_get_main_queue(),^ {
            handler(imageArray);
        });
    });
}

@end
于 2012-12-18T18:08:30.140 回答