NSURLConnection 下载多张图片

2023-12-08

我正在尝试从 XML 提要中存储的 URL 下载多个图像。从 XML 获取图像 url 工作正常。但是,NSURLConnection 正在创建空文件,但数据已按照 NSLog 中的说明接收。在connectionDidFinishLoading:(NSURLConnection *)connection,收到数据和正确的字节,问题是如何使收到的数据写入正确的文件。

半工作代码:

-(void)parsingComplete:(XMLDataSource*)theParser 
{
    /*  iterate through the Categories and create the 
        sub-directory if it does not exist  
     */
    for (int i = 0; i < [categories count]; i++) {
        NSString *cat      = [NSString stringWithFormat:@"%@/%@",BASE_DIR,[[categories objectAtIndex:i] objectForKey:@"name"]];
        NSString *catName  = [[categories objectAtIndex:i] objectForKey:@"name"];
        NSArray  *catArray = [[categories objectAtIndex:i] objectForKey:@"images"];

        /*  create the sub-direcotry naming it the #category# key  */
        if (![FILEMANAGER fileExistsAtPath:cat]) {
            [FILEMANAGER createDirectoryAtPath:cat withIntermediateDirectories:NO attributes:nil error:nil];
        }

        //NSLog(@"\n\nCategory: %@",cat);
        for (int x = 0; x < [catArray count]; x++) {
            //NSLog(@"Image: %@",[[catArray objectAtIndex:x] objectForKey:@"imageUrl"]);   
            /*  download each file to the corresponding category sub-directory  */
            fileOut = [NSString stringWithFormat:@"%@/%@_0%i.jpg",cat,catName,x];

            NSURLRequest *imageRequest = 
            [NSURLRequest requestWithURL:[NSURL URLWithString:[[catArray objectAtIndex:x] objectForKey:@"imageUrl"]]
                             cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30.0];
            NSURLConnection *imageConnection = [[NSURLConnection alloc] initWithRequest:imageRequest delegate:self];

            int counter = 0;
            //BOOL result = NO;
            if(imageConnection)
            {
                NSLog(@"Counter: %i",counter++);
                receivedData = [[NSMutableData data] retain];
                /*result = */[receivedData writeToFile:fileOut atomically:YES];
            }
            /*
                if (!result) NSLog(@"Failed"); else NSLog(@"Successful");
             */
        }
    }
}

#pragma mark NSURLConenction

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response  {  
    [receivedData setLength:0];  
} 
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data  {  
    [receivedData appendData:data];
}  
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    // release the connection, and the data object
    [connection release];
    // receivedData is declared as a method instance elsewhere
    [receivedData release];
    // inform the user
    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection  
{  
    // do something with the data  
    // receivedData is declared as a method instance elsewhere  
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);  
    NSString *aStr = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];  
    // release the connection, and the data object  
    //[receivedData release];  
} 

您必须等到连接告诉您连接已完成,然后才能写入数据。连接在另一个线程上处理;如果您尝试立即在原始线程上访问数据,那么其中将不会有任何内容。

你应该移动writeToFile:调用到末尾connectionDidFinishLoading:,或从那里调用的另一个方法。这是您知道数据已全部收集的第一点。

我还建议创建NSMutableData实例在didRecieveResponse:,以便您知道它在正确的时间可用。这将更具可读性/易于理解。您可以将委托方法视为一个集体“范围”——数据仅在其中使用,因此应该在其中一个方法内部创建。

回复您的评论:

一种可能性是,由于您有很多需要围绕这一下载完成的工作,并且似乎没有触及 GUI,因此运行整个parsingComplete:后台线程上的方法,并使用+[NSURLConnection sendSynchronousRequest:returningResponse:error:]。这样,您的代码将只等待数据返回,并且您可以在数据返回后立即编写它sendSynchronous...呼叫返回。

NSError * err;
NSURLResponse * response;
NSData * receivedData = [NSURLConnection sendSynchronousRequest:imageRequest
                                              returningResponse:&response
                                                          error:&err];
if( !receivedData ){
    /* Handle error */
}
/* Check response */

BOOL result = [receivedData writeToFile:fileOut atomically:YES];
/* check result, etc. */
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

NSURLConnection 下载多张图片 的相关文章

随机推荐

  • OSX 以编程方式调用声级图形

    我有一个可以在 OSX 下更改音量的应用程序 它缺少的是按下声音上 下键时提供的视觉反馈 有谁知道如何以编程方式调用该行为 谢谢 以下是 George Warner 和 Casey Fleser 编写的一些代码 用于实现此目的 仔细想想这是
  • 对 Java 中另一个类中实例化/初始化的对象的引用变量

    我问的原因是因为我收到 NullPointerException 我现在这很容易 但我是一个相当新的编程人员 发现这有点令人困惑 假设我已经初始化了一个类中的一个对象 并且想要从另一个类访问同一对象 就像现在 我正在开发一个小型国际象棋游戏
  • Linux 中 Socket 的发送缓冲区为空?

    有没有办法检查 TCP 连接的发送缓冲区是否完全为空 到目前为止我还没有找到任何东西 只是想确保在仍有数据传输到某个客户端时我的服务器没有关闭连接 我正在使用轮询来检查是否能够在非阻塞套接字上发送数据 但这样我就无法知道是否所有内容都已发送
  • CSS多行省略号跨浏览器

    我的网页中有一个具有固定宽度和高度的 div 以下 css 仅适用于单行文本 overflow hidden text overflow ellipsis white space nowrap 如何使用具有跨浏览器兼容性的纯 css 在该
  • 如何检查是否授予“android.permission.PACKAGE_USAGE_STATS”权限?

    背景 我正在尝试获取应用程序启动的统计信息 在 Lollipop 上可以使用使用情况统计管理器类 本身 原帖here 显现
  • 如何在一般github的markdown中显示数学方程(不是github的博客)

    经过调查 我发现 mathjax 可以做到这一点 但是当我在 markdown 文件中编写一些示例时 它没有显示正确的方程 我已将其添加到 markdown 文件的头部 并输入 mathjax 语句 E mc 2 x 1 2 frac b
  • 如何使谷歌地图中的标记图像闪烁

    我在地图上有一些标记 代码部分在这里 var icons media green png media red png media blue png media yellow png var marker new google maps Ma
  • 折线的距离

    我正在折线中工作 我需要获得它的距离 因此 如果有人可以提供帮助 我将非常感激 此致 这是我的代码 function polyline downloadUrl xmlPolyline asp function data var xml xm
  • javafx fxml 组合框错误

    我试图将字符串添加到 javafx 组合框 但我不断收到上述错误 no suitable method found for add String method Collection add CAP 1 is not applicable a
  • Java 是否保证 Object.getClass() == Object.getClass()?

    我在这里确实指的是身份平等 例如 以下内容是否总是打印true System out println foo getClass fum getClass 是的 类标记是唯一的 对于任何给定的类加载器来说 IE 您将始终获得对同一物理对象的引
  • Android 应用程序 - 尝试在空对象引用上调用接口方法“int java.util.List.size()”

    我正在创建一个在网格视图中显示电影海报的应用程序 我正在使用 themoviedb org 的 API 问题是当我运行我的应用程序时出现以下错误 并且我正在努力修复它 07 18 20 27 39 244 2751 2751 E Andro
  • 如何在 swift 中使用 Gmail api 发送电子邮件

    The 邮箱API没有关于如何执行此操作的明确文档 我一直在尝试this但空气中有很多东西 我已经寻找过这样的外部资源 Source 1 and Source 2 第一个似乎利用了api的潜力 使用了函数queryForUsersMessa
  • jQuery 无法与我的 Blazor 应用程序正常工作

    我有以下脚本 它在从浏览器启动的简单 html 文件中运行良好 scroll to click event gt whatever here 但是 当将其与 Blazor 一起使用时 单击我的按钮时不会触发它 我找到了一个解决方法 即将第一
  • 如何订阅通过@angular/cdk/portal注入的组件的Observable?

    我正在尝试实现一个基本的 非常基本的 模式实现 我有一个ModalService and a ModalComponent The ModalService创建一个实例ModalComponent并使用 angular cdk portal
  • 验证 Azure Active Directory 中是否存在用户帐户

    我需要遵循一些业务规则 从 ASP NET Core 2 应用程序向用户发送电子邮件 但是 我需要确保电子邮件发送到的帐户确实存在 由于某种原因 该帐户可能不再有效 客户正在使用 Azure Active Directory 因此我需要以某
  • 使用索引替换值 [R]

    我正在尝试使用索引来识别哪些行要根据另一个 DF 的联接创建新列 使用索引时我无法执行 match df1 lt data frame A c A C E B c 1 3 5 df2 lt data frame A c A C E C c
  • 确定 C 中动态分配内存的大小

    C 有没有办法找出动态分配的内存的大小 例如 之后 char p malloc 100 有没有办法找出与相关的内存大小p 没有找到此信息的标准方法 然而 一些实现提供了类似的功能msize去做这个 例如 msize在 Windows 上 m
  • Selenium WebDriver - 没有驱动程序适合我

    我正在尝试运行 Selenium 测试 我正在使用 C 我尝试过的每个驱动程序都存在问题 Chrome var options new OpenQA Selenium Chrome ChromeOptions options BinaryL
  • 解压缩 gzip 压缩的 http 响应

    我正在使用 phpfile get contents 函数执行 HTTP 请求 为了节省带宽 我决定添加 Accept Encoding gzip 标头使用stream context create 明显地 file get content
  • NSURLConnection 下载多张图片

    我正在尝试从 XML 提要中存储的 URL 下载多个图像 从 XML 获取图像 url 工作正常 但是 NSURLConnection 正在创建空文件 但数据已按照 NSLog 中的说明接收 在connectionDidFinishLoad