iOS Objective-C 文件下载教程 - 完整代码示例
在 iOS 开发中,可以使用 Objective-C 来下载文件。以下是一个简单的示例代码:
// 创建一个 NSURL 对象,指定要下载的文件的 URL
NSURL *url = [NSURL URLWithString:'http://example.com/file.txt'];
// 创建一个 NSURLSession 对象
NSURLSession *session = [NSURLSession sharedSession];
// 创建一个下载任务
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
if (error) {
NSLog('下载失败: %@', error);
return;
}
// 获取下载后的文件的临时存储位置
NSString *temporaryPath = [location path];
// 将文件移动到应用的文档目录
NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *destinationPath = [documentsPath stringByAppendingPathComponent:'file.txt'];
NSError *moveError;
[[NSFileManager defaultManager] moveItemAtPath:temporaryPath toPath:destinationPath error:&moveError];
if (moveError) {
NSLog('文件移动失败: %@', moveError);
return;
}
NSLog('文件下载成功,并已保存到: %@', destinationPath);
}];
// 开始下载任务
[task resume];
以上代码使用 NSURLSession 来进行文件下载,下载完成后将文件移动到应用的文档目录。你可以根据自己的需求修改代码。
原文地址: https://www.cveoy.top/t/topic/pmB3 著作权归作者所有。请勿转载和采集!