如何从url下载数据包含json fileurl objective C

时间:2015-09-17 04:29:33

标签: ios objective-c json nsdata nsurl

我正在为iOS应用程序做一个商店部分,它有两个页面(商店中的voicePack显示列表的第一页和voicePack内部的语音显示细节的第二页)。

单击voicePackList中的任何单元格转到下一页并在下一页中存在一个名称为DOWNLOAD的按钮,当我单击该按钮时,我想要下载并保存在文档文件夹中。这是我在按下按钮处理中所做的代码:

    - (void)downloadingVoice {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"Starting Download ...");
        NSString *downloadUrl = @"10.3.1.228:9000/files";
        NSURL *url = [NSURL URLWithString:downloadUrl];
        NSData *urlData = [NSData dataWithContentsOfURL:url];

        if (urlData) {

            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *voiceDirectory = [paths objectAtIndex:0];
            NSString *voicePaths = [NSString stringWithFormat:@"%@%@", voiceDirectory,@"voice.mp3"];

            dispatch_async(dispatch_get_main_queue(), ^{
                [urlData writeToFile:voicePaths atomically:YES];
                NSLog(@"Saved voice files");
            });
        }
    });
}

- (void)btnDownloadClicked:(id)sender {
    NSLog(@"Downloading Voice . . .");

    [self downloadingVoice];
}

以下是我如何将按钮放在声音列表下方:

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 60.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    // if(tableView == self.shopTableView) {
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 40)];
    UIButton *download = [UIButton buttonWithType:UIButtonTypeCustom];
    [download setTitle:@"Download" forState:UIControlStateNormal];
    [download addTarget:self action:@selector(btnDownloadClicked:) forControlEvents:UIControlEventTouchUpInside];
    [download setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    download.frame = CGRectMake(0, 0, 130, 30);
    [footerView addSubview:download];

    return footerView;
}

当我点击按钮并放置一些断点时,当我检查urlData和downloadUrl时,它会在if (urlData)之后结束,它说:

2015-09-17 10:53:01.926 Selfie[87197:674517] Starting Download ...

(lldb) po urlData
error: Couldn't materialize: couldn't get the value of variable urlData: no location, value may have been optimized out
Errored out in Execute, couldn't PrepareToExecuteJITExpression
(lldb) po downloadUrl
error: Couldn't materialize: couldn't get the value of variable downloadUrl: variable not available
Errored out in Execute, couldn't PrepareToExecuteJITExpression

任何人都可以帮我解决这个问题..我真的非常感谢你的帮助..

1 个答案:

答案 0 :(得分:0)

首先,您正在同步获取语音数据,这是不可取的,因为这会挂起您的主线程。您可以使用主线程来显示加载覆盖,并允许用户在花费太多时间时取消下载操作。请使用以下方法进行异步调用。

其次,您能否确保在您尝试访问文件的网络上打开您指向的URL。如果这是本地服务器,最好放置localhost而不是IP地址。

- (void)fetchFilesAsynchronously {
    NSURL *myUrl = [NSURL URLWithString:@"http://10.3.1.228:9000/files"];
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:myUrl cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0];

    // Add headers as per your need
    [urlRequest setValue:@"value" forHTTPHeaderField:@"key"];

    // Add body as per your need
    NSDictionary *body = @{@"key" : @"value"};
    NSData *requestBodyData = [NSJSONSerialization dataWithJSONObject:body options:NSJSONWritingPrettyPrinted error:nil];
    [urlRequest setHTTPBody:requestBodyData];

    [NSURLConnection sendAsynchronousRequest:urlRequest queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *iResponse, NSData *iData, NSError *iConnectionError) {
        // Handle response here
    }];
}

第三,针对您的调试器问题,请查看this thread