如何使用AFNetworking 3.0下载文件并保存到本地?

时间:2016-02-01 18:31:21

标签: ios objective-c

在我的项目中,我需要下载一个小视频。在之前的版本中,我使用了这个:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/4.1.0/imagesloaded.pkgd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/masonry/4.0.0/masonry.pkgd.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<div class="container-fluid">
  <div class="postrow row">
    <div id="masonry-container">

      <article class="post-listview col-lg-3 col-xs-6">
        <div class="articleinner">
          <div class="thumbandtitle">
            <img src="http://placehold.it/350x150" class="img-responsive post-thumbnail">
            <div class="post-overlay">
              <div class="post-overlay-text">
                <h2><a href="#">ONE</a></h2>
                <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
                  book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchangeLorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's
                  standard</p>
              </div>
            </div>
          </div>
          <p class="post-info">
            <i class="post-icon post-date-icon fa fa-calendar"></i>time
            <span class="separator"></span>
            <span class="tagspan"><i class="post-icon post-author-icon fa fa-user"></i><a href="x">authorname</a></span>
            <span class="separator"></span>
            <span class='tagspan'><i class="post-icon post-tags-icon fa fa-tags"></i>tag1, tag2, tag3...</span>
          </p>
        </div>
      </article>

      <article class="post-listview col-lg-3 col-xs-6">
        <div class="articleinner">
          <div class="thumbandtitle">
            <img src="http://placehold.it/350x150" class="img-responsive post-thumbnail">
            <div class="post-overlay">
              <div class="post-overlay-text">
                <h2><a href="#">TWO</a></h2>
                <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
                  book. It has survived not only five centuries, but also the leap into electronic typesetting, rema
                </p>
              </div>
            </div>
          </div>
          <p class="post-info">
            <i class="post-icon post-date-icon fa fa-calendar"></i>time
            <span class="separator"></span>
            <span class="tagspan"><i class="post-icon post-author-icon fa fa-user"></i><a href="x">authorname</a></span>
            <span class="separator"></span>
            <span class='tagspan'><i class="post-icon post-tags-icon fa fa-tags"></i>tag1, tag2, tag3...</span>
          </p>
        </div>
      </article>

      <article class="post-listview col-lg-3 col-xs-6">
        <div class="articleinner">
          <div class="thumbandtitle">
            <img src="http://placehold.it/350x150" class="img-responsive post-thumbnail">
            <div class="post-overlay">
              <div class="post-overlay-text">
                <h2><a href="#">THREE</a></h2>
                <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry.</p>
              </div>
            </div>
          </div>
          <p class="post-info">
            <i class="post-icon post-date-icon fa fa-calendar"></i>time
            <span class="separator"></span>
            <span class="tagspan"><i class="post-icon post-author-icon fa fa-user"></i><a href="x">authorname</a></span>
            <span class="separator"></span>
            <span class='tagspan'><i class="post-icon post-tags-icon fa fa-tags"></i>tag1, tag2, tag3...</span>
          </p>
        </div>
      </article>

      <article class="post-listview col-lg-3 col-xs-6">
        <div class="articleinner">
          <div class="thumbandtitle">
            <img src="http://placehold.it/350x150" class="img-responsive post-thumbnail">
            <div class="post-overlay">
              <div class="post-overlay-text">
                <h2><a href="#">FOUR</a></h2>
                <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
                  book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchange setting industry. Lorem Ipsum has been the industry's standard dum</p>
              </div>
            </div>
          </div>
          <p class="post-info">
            <i class="post-icon post-date-icon fa fa-calendar"></i>time
            <span class="separator"></span>
            <span class="tagspan"><i class="post-icon post-author-icon fa fa-user"></i><a href="x">authorname</a></span>
            <span class="separator"></span>
            <span class='tagspan'><i class="post-icon post-tags-icon fa fa-tags"></i>tag1, tag2, tag3...</span>
          </p>
        </div>
      </article>

      <article class="post-listview col-lg-3 col-xs-6">
        <div class="articleinner">
          <div class="thumbandtitle">
            <img src="http://placehold.it/350x150" class="img-responsive post-thumbnail">
            <div class="post-overlay">
              <div class="post-overlay-text">
                <h2><a href="#">FIVE</a></h2>
                <p>xyz</p>
              </div>
            </div>
          </div>
          <p class="post-info">
            <i class="post-icon post-date-icon fa fa-calendar"></i>time
            <span class="separator"></span>
            <span class="tagspan"><i class="post-icon post-author-icon fa fa-user"></i><a href="x">authorname</a></span>
            <span class="separator"></span>
            <span class='tagspan'><i class="post-icon post-tags-icon fa fa-tags"></i>tag1, tag2, tag3...</span>
          </p>
        </div>
      </article>

      <article class="post-listview col-lg-3 col-xs-6">
        <div class="articleinner">
          <div class="thumbandtitle">
            <img src="http://placehold.it/350x150" class="img-responsive post-thumbnail">
            <div class="post-overlay">
              <div class="post-overlay-text">
                <h2><a href="#">SIX</a></h2>
                <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
                  book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchange Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's
                </p>
              </div>
            </div>
          </div>
          <p class="post-info">
            <i class="post-icon post-date-icon fa fa-calendar"></i>time
            <span class="separator"></span>
            <span class="tagspan"><i class="post-icon post-author-icon fa fa-user"></i><a href="x">authorname</a></span>
            <span class="separator"></span>
            <span class='tagspan'><i class="post-icon post-tags-icon fa fa-tags"></i>tag1, tag2, tag3...</span>
          </p>
        </div>
      </article>

      <article class="post-listview col-lg-3 col-xs-6">
        <div class="articleinner">
          <div class="thumbandtitle">
            <img src="http://placehold.it/350x150" class="img-responsive post-thumbnail">
            <div class="post-overlay">
              <div class="post-overlay-text">
                <h2><a href="#">SEVEN</a></h2>
                <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
                  book. It has survived not only five centuries, but also the leap into electronic typesetting, remain
                </p>
              </div>
            </div>
          </div>
          <p class="post-info">
            <i class="post-icon post-date-icon fa fa-calendar"></i>time
            <span class="separator"></span>
            <span class="tagspan"><i class="post-icon post-author-icon fa fa-user"></i><a href="x">authorname</a></span>
            <span class="separator"></span>
            <span class='tagspan'><i class="post-icon post-tags-icon fa fa-tags"></i>tag1, tag2, tag3...</span>
          </p>
        </div>
      </article>

      <article class="post-listview col-lg-3 col-xs-6">
        <div class="articleinner">
          <div class="thumbandtitle">
            <img src="http://placehold.it/350x150" class="img-responsive post-thumbnail">
            <div class="post-overlay">
              <div class="post-overlay-text">
                <h2><a href="#">EIGHT</a></h2>
                <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
                  book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchange Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's
                </p>
              </div>
            </div>
          </div>
          <p class="post-info">
            <i class="post-icon post-date-icon fa fa-calendar"></i>time
            <span class="separator"></span>
            <span class="tagspan"><i class="post-icon post-author-icon fa fa-user"></i><a href="x">authorname</a></span>
            <span class="separator"></span>
            <span class='tagspan'><i class="post-icon post-tags-icon fa fa-tags"></i>tag1, tag2, tag3...</span>
          </p>
        </div>
      </article>

      <article class="post-listview col-lg-3 col-xs-6">
        <div class="articleinner">
          <div class="thumbandtitle">
            <img src="http://placehold.it/350x150" class="img-responsive post-thumbnail">
            <div class="post-overlay">
              <div class="post-overlay-text">
                <h2><a href="#">NINE</a></h2>
                <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
                  book.
                </p>
              </div>
            </div>
          </div>
          <p class="post-info">
            <i class="post-icon post-date-icon fa fa-calendar"></i>time
            <span class="separator"></span>
            <span class="tagspan"><i class="post-icon post-author-icon fa fa-user"></i><a href="x">authorname</a></span>
            <span class="separator"></span>
            <span class='tagspan'><i class="post-icon post-tags-icon fa fa-tags"></i>tag1, tag2, tag3...</span>
          </p>
        </div>
      </article>

    </div>
  </div>
</div>

如何在AFNetworking 3.0中执行此操作?

2 个答案:

答案 0 :(得分:15)

此代码:

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
    return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    NSLog(@"File downloaded to: %@", filePath);
}];
[downloadTask resume];

在项目的自述文件中:https://github.com/AFNetworking/AFNetworking

答案 1 :(得分:5)

我意识到最初的问题出现在Obj-C中,但是这出现在谷歌搜索中,所以对于其他任何绊倒它并且需要Swift版本的@Lou Franco的答案的人来说,这里是:

let configuration = URLSessionConfiguration.default
let manager = AFURLSessionManager(sessionConfiguration: configuration)
let url = URL(string: "http://example.com/download.zip")! // TODO: Don't just force unwrap, handle nil case
let request = URLRequest(url: url)

let downloadTask = manager.downloadTask(
    with: request,
    progress: { (progress: Progress) in
                    print("Downloading... progress: \(String(describing: progress))")
                },

    destination: { (targetPath: URL, response: URLResponse) -> URL in
                    // TODO: Don't just force try, add a `catch` block
                    let documentsDirectoryURL = try! FileManager.default.url(for: .documentDirectory,
                                                                             in: .userDomainMask,
                                                                             appropriateFor: nil,
                                                                             create: false)

                    return documentsDirectoryURL.appendingPathComponent(response.suggestedFilename!) // TODO: Don't just force unwrap, handle nil case
                },

    completionHandler: { (response: URLResponse, filePath: URL?, error: Error?) in
                            print("File downloaded to \(String(describing: filePath))")
                        }
)

downloadTask.resume()

这里有几点说明:

  • 这是Swift 3 / Swift 4
  • 我还添加了一个progress闭包(只是一个print语句)。但当然,如原始示例中那样传递nil是完全没错的。
  • 有三个地方(标有TODO:)没有错误处理,事情可能会失败。显然你应该处理这些错误,而不仅仅是崩溃。