HOME > NSURLSession
NSURLConnectionの進化版のような立ち位置に私は感じております。アプリがバックグラウンドになっても通信処理を続けてくれる優れものです。
以前まではどうやら音声や位置情報だけに限られていましたが、このクラスによって大きなデータをユーザに気持ちよくDLしてもらうことも可能にです。
プロトコルはHTTPだけですが、
ZIPファイルなんかを大量にデータを詰め込んでDLする等利用価値はかなり高いのではと思います。NSURLConnectionは汎用的でFTP等の通信プロトコルにも対応していますので、
臨機応変にご利用いただければ感謝です。
NSObject
↑
NSURLSession
参考:NSURLSession のまとめ
参考:Foundation Framework Reference NSURLSession Class Reference
参考:iOS 7で一新された通信周り〜NSURLSessionってなに?〜
参考:iOSハンズオントレーニング通信(NSURLConnection/NSURLSession)編
Swifサラリーマンのサーバにある25KB程度のZIPをダウンロードするサンプルです。
import UIKit
class ViewController: UIViewController, NSURLSessionDownloadDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let newsUrlString = "http://swift-salaryman.com/files/download/ssziparchive_sample.zip"
//ネットワーク上からZIPをダウンロードする
var sessionConfiguration:NSURLSessionConfiguration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("com.company")
var session:NSURLSession! = NSURLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)
var downloadTask:NSURLSessionDownloadTask = session.downloadTaskWithURL(NSURL(string:newsUrlString)!);
downloadTask.resume()
}
//ZIPファイルをネットワーク上からDL完了後に呼ばれる
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL){
println(location);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
このZIPファイルを解凍する方法は過去記事のSSZipArchiveをご一読いただければ感謝です
少しだけNSURLSessionConfigurationの設定に関して説明します。
ホストに対しての同時接続の上限です。バックグラウンドで実行できる非同期のNSURLSessionですので重複しますので、 ホストに対しての上限をこのプロパティで調整することが可能です
こちらはセルラーアクセスが可能かどうかです。Wifi接続ではなく3Gとか4Gとかですね。通信をWifiだけに限定して ユーザフレンドリーにしたりも可能です。僕的にも4Gの時なんかに大きなファイルを勝手にDLしているのは止めてほしいです。。。
リクエスト毎のタイムアウトと判断する閾値の設定です。デフォルトは60秒。
非同期セッション関連の作業は面倒な処理が多いと思っていましたが、ソースを整理してみると以外に短くほっとしました。 よろしければご利用いただければ感謝です:)
2021-05-14 14:21:41 | The pitfalls of Filetransfer in watchconnectivity on WatchOS. And how to avoid.
AppleWatch it succeeds with the actual machine, but if it is a simulator, it will fail、、、
When I... |
2021-05-06 14:04:37 | Line's animation stamp production pitfalls 、、、 failure story
I tried to make a LINE sticker during Golden Week.
I made it and applied, but it was different f... |
2021-04-22 14:54:53 | Cool carousel carefully selected 3 points! Astringent image slider using WebGL.
I was on a trip to find a cool slider yesterday.
It's simple, easy to use, and has a good de... |
Tweet
![]() |
|||
|