iOS Objective-C 文件下载:完整示例和代码
在 iOS 中,可以使用 Objective-C 编写代码来下载文件。以下是一个简单的示例:
// 创建一个下载任务
NSURL *url = [NSURL URLWithString:'https://example.com/file.txt'];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSessionDownloadTask *downloadTask = [[NSURLSession sharedSession] downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
if (error) {
NSLog('下载失败: %@', error);
} else {
// 将下载的文件移动到指定的目录
NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:'file.txt'];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager moveItemAtURL:location toURL:[NSURL fileURLWithPath:filePath] error:nil];
NSLog('下载完成,文件保存在: %@', filePath);
}
}];
// 启动下载任务
[downloadTask resume];
在上面的示例中,我们首先创建了一个 NSURLRequest 对象,用于指定下载文件的 URL。然后,我们使用 NSURLSession 的 downloadTaskWithRequest:completionHandler: 方法创建了一个下载任务。在完成下载后,我们可以在 completionHandler 中获取到下载的文件的临时存储位置 location。接下来,我们将下载的文件移动到指定的目录(在这个示例中是应用程序的文档目录),并打印出文件的保存路径。
注意: 该示例中的下载任务是在后台线程执行的,如果需要在主线程执行 UI 操作,需要使用适当的调度方法,例如 dispatch_async 或 NSOperationQueue。
原文地址: https://www.cveoy.top/t/topic/pmxZ 著作权归作者所有。请勿转载和采集!