Swift - NSURLSession downloading in background?

2019-09-18 18:51发布

问题:

I'm creating an iOS app by swift that is as same as the AliExpress iOS app. This App has ability that connect to our site and download all of data from JSON api online. Now, I wanna download the images of the icons and banner slider from our site by JSON api in main page. But I don't know how i can do it. Do I use queues or background functions like in android? Also, I'm an android developer and i know how i can do this in android. You can guide me by this way ,too. please guide me by sample codes or description of its logic.

回答1:

Please refer following link for tutorial

http://www.raywenderlich.com/51127/nsurlsession-tutorial

Apple documentation can be found on following link

https://developer.apple.com/library/prerelease/ios/documentation/Foundation/Reference/NSURLSession_class/

Swift example can be found here

http://jamesonquave.com/blog/making-a-post-request-in-swift/

I have also created a demo for the same

https://github.com/Gagan5278/SessionDownload

Let me know if you want more on this.



回答2:

You have the seed of your answer in the title of your question. You want to create an NSURLSession and add NSURLDownloadTasks to it. That class does all the work for you.

A quick search on Github reveals this repository that claims to offer an async download queue in Swift:

https://github.com/Gurpartap/Cheapjack

(I haven't used that one. You can either build it into your project or look at the code and use it to implement your own download sessions.)

There is also AlamoFire, another swift library that has built-in JSON support.