菜鸟教程小白 发表于 2022-12-11 19:18:19

ios - 用swift和objective-c下载文件


                                            <p><p>我有 2 个项目,使用 2 种不同的语言。 <code>Objective-c</code> 项目和 <code>swift</code> 项目从 url 下载文件。 </p>

<p>问题在于 <code>objective-c</code> 中文件的下载速度比 <code>swift</code> 中更快。为什么会这样?如何解决?</p>

<p>我的快速代码:</p>

<pre><code>override func viewDidLoad() {
    super.viewDidLoad()

    let backgroundSessionConfiguration = URLSessionConfiguration.background(withIdentifier: &#34;backgroundSession&#34;)
    backgroundSession = Foundation.URLSession(configuration: backgroundSessionConfiguration, delegate: self, delegateQueue: OperationQueue.main)
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {



    if indexPath.row &gt; 0 { print(indexPath.row)

      let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
      print(path)
      let documentDirectoryPath:String = path
      let fileManager = FileManager()
      let destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath.appendingFormat(&#34;/file\(indexPath.row).mp3&#34;))


      if fileManager.fileExists(atPath: destinationURLForFile.path){

            self.performSegue(withIdentifier: &#34;detailSegue&#34;, sender: self)
            print(indexPath.row)
      }else{

            index = indexPath.row

            let url = URL(string: &#34;link\(indexPath.row).mp3&#34;)!
            downloadTask = backgroundSession.downloadTask(with: url)
            downloadTask.resume()


            circularProgressView = FFCircularProgressView(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(24), height: CGFloat(24)))
            tableView.cellForRow(at: indexPath)?.accessoryView = self.circularProgressView
            self.view.addSubview(circularProgressView)
            circularProgressView.startSpinProgressBackgroundLayer()

      }
    }   
}

//MARK: URLSessionDownloadDelegate
func urlSession(_ session: URLSession,
                downloadTask: URLSessionDownloadTask,
                didFinishDownloadingTo location: URL){

    let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
    let documentDirectoryPath:String = path
    let fileManager = FileManager()
    let destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath.appendingFormat(&#34;/file\(index).mp3&#34;))

    do {
      try fileManager.moveItem(at: location, to: destinationURLForFile)
      }catch{
            print(&#34;An error occurred while moving file to destination url&#34;)
      }
}
func urlSession(_ session: URLSession,
                downloadTask: URLSessionDownloadTask,
                didWriteData bytesWritten: Int64,
                totalBytesWritten: Int64,
                totalBytesExpectedToWrite: Int64){

    progress1 = Int(Float(totalBytesWritten))
    total1 = Int(Float(totalBytesExpectedToWrite))
    let percentage = String(format: &#34;%.f%%&#34;, ((self.progress1 / self.total1) * 100))
    (print(String(format: percentage, &#34;%.f%%&#34;)))
    DispatchQueue.main.async(execute: {() -&gt; Void in
      self.circularProgressView.progress = (CGFloat(self.progress1) / CGFloat(self.total1))
      self.circularProgressView.stopSpinProgressBackgroundLayer()
    })
}

//MARK: URLSessionTaskDelegate
func urlSession(_ session: URLSession,
                task: URLSessionTask,
                didCompleteWithError error: Error?){
    downloadTask = nil
    if (error != nil) {
      print(error!.localizedDescription)
    }else{
      print(&#34;The task finished transferring data successfully&#34;)
    }
}
</code></pre>

<p>我的 Objective-C 代码:</p>

<pre><code>- (void)viewDidLoad
{
;

_session = delegate:self delegateQueue:];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{


if (indexPath.row == 1) {
      NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
      NSString *documentsDirectory = ;
      NSString *filePath = ;
      BOOL fileExists = [ fileExistsAtPath:filePath isDirectory:false];
      if (!fileExists) {

            UIAlertController * alert = [UIAlertController
                                       alertControllerWithTitle:@&#34;&#34;
                                       message:@&#34;&#34;
                                       preferredStyle:UIAlertControllerStyleActionSheet];
            UIAlertAction* actionAdd = [UIAlertAction
                                        actionWithTitle:@&#34;&#34;
                                        style:UIAlertActionStyleDefault
                                        handler:^(UIAlertAction * action)
                                        {
                                          ;

                                          _url1 =;
                                          _downloadTask1 = ;
                                          ;

                                          self.circularPV1 = [ initWithFrame:CGRectMake(0, 0, 24, 24)];

                                          .accessoryView = self.circularPV1;
                                          ;

                                          ;

                                        }];

            UIAlertAction* actionCancel = [UIAlertAction
                                           actionWithTitle:@&#34;&#34;
                                           style:UIAlertActionStyleCancel
                                           handler:^(UIAlertAction * action)
                                           {
                                             ;
                                           }];
            ;
            ;
            alert.popoverPresentationController.sourceView = self.view;
            alert.popoverPresentationController.sourceRect = CGRectMake(self.view.bounds.size.width / 3.4, self.view.bounds.size.height / 4.0, 1.0, 1.0);
            ;
      }
      if (fileExists) {
            ;
      }
    }
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{

if (downloadTask == _downloadTask1) {

    _paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    _documentsDirectory1 = ;
    NSFileManager *fileManager = ;
    NSURL *newLocation = ];
    NSError *error;
    ;
}
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWrittentotalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite;
{
if( downloadTask == _downloadTask1){
    self.progress1 = (float) totalBytesWritten;
    self.total1 =(float) totalBytesExpectedToWrite;
    NSString *percentage = ;
    (NSLog (percentage, @&#34;%.f%%&#34;));
    dispatch_async(dispatch_get_main_queue(), ^{
      ;
      ;
    });
}
}
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>您的 swift 代码正在使用后台 URLsession 。操作系统对这些下载的优先级较低。 </p>

<p>如果您不需要使用后台 session ,您可以在创建 session 时模仿 Objective C 代码:</p>

<pre><code>session = URLSession(configuration:URLSessionConfiguration.default delegate:self delegateQueue:OperationQueue.main)
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 用swift和objective-c下载文件,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/42886955/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/42886955/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 用swift和objective-c下载文件