在 iOS 开发中,可以使用 Objective-C 来下载文件并将其保存到沙盒路径中。下面是一个简单的示例:

  1. 首先,导入需要使用的库文件:
#import <Foundation/Foundation.h>
  1. 创建一个方法来下载文件:
- (void)downloadFileFromURL:(NSString *)urlString {
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLSessionDownloadTask *downloadTask = [[NSURLSession sharedSession] downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
        if (error) {
            NSLog('下载出错:%', error.localizedDescription);
            return;
        }
        
        // 获取文件保存的路径
        NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        NSString *filePath = [documentsPath stringByAppendingPathComponent:[response suggestedFilename]];
        
        // 将文件从临时位置移动到目标路径
        NSError *moveError;
        [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:filePath] error:&moveError];
        if (moveError) {
            NSLog('保存文件出错:%', moveError.localizedDescription);
            return;
        }
        
        NSLog('文件下载成功,保存路径:%', filePath);
    }];
    
    [downloadTask resume];
}
  1. 调用下载方法:
NSString *fileURLString = 'http://example.com/file.txt';
[self downloadFileFromURL:fileURLString];

在上面的示例中,我们首先创建了一个NSURL对象来表示文件的 URL,然后使用NSURLSessionDownloadTask来下载文件。在下载完成后,我们将文件从临时位置移动到目标路径,这里使用的是应用程序的Documents目录,你也可以根据需要选择其他路径。

需要注意的是,在使用NSURLSessionDownloadTask下载文件时,下载任务是在后台线程中进行的,因此如果需要在主线程更新 UI 或执行其他操作,需要在适当的地方使用 GCD 或其他方式切换到主线程。


原文地址: https://www.cveoy.top/t/topic/pmx6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录