サーバーから多くの、しかしかなり小さい.jsonおよび.jpgファイルをダウンロードする必要があるiPadアプリを作成しています。
だから私はこのようにやっています:
///Function to allow for recursive calls to syncronize inspections sequentially.
func getInspection(ip: String, view: sensorSyncronizationDelegate, idarr:[IdData], appDelegate: AppDelegate){
let inspectionID = idarr[0]
var newArr = idarr
//A task is created for each inspection that needs to be downloaded, and the json is parsed and added to the database.
if self.session != nil {
let inspectionURL = NSURL(string: "http://\(ip)/inspections/\(inspectionID.id!).json")
let inspectionTask = self.session!.dataTaskWithURL(inspectionURL!) { (data, response, error) in
//If data is nil, end the task.
if data == nil {
view.setInspectionSyncCompleted()
view.completion("Error: Timeout please ensure Instrument is on, and attempt syncronization again")
print(error)
return
}
//if newArr is NOT empty make a recursiv call to getInspection()
newArr.removeAtIndex(0)
if !newArr.isEmpty{
self.getInspection(ip, view: view, idarr: newArr, appDelegate: appDelegate)
}else{
self.syncMisc(ip, view: view)
}
(私は常に dataTaskWithURL を使用しています)
そして、これがセッションのセットアップ方法です。
var session : NSURLSession?
///Function to set up various http configurations, and call the various syncronization functions.
func syncWithSensor(view: sensorSyncronizationDelegate, ip: String!){
//Session Configuration
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.allowsCellularAccess = true
config.timeoutIntervalForRequest = 30
config.timeoutIntervalForResource = 60
config.URLCache = nil
//Authentication config
let userpasswordString = "MAMA:PassWord"
let userpasswordData = userpasswordString.dataUsingEncoding(NSUTF8StringEncoding)
let base64encodedCreds = userpasswordData!.base64EncodedStringWithOptions([])
let authString = "Basic \(base64encodedCreds)"
config.HTTPAdditionalHeaders = ["Authorization" : authString, "Connection" : "Upgrade"]
session = NSURLSession(configuration: config)
//Check if for some reason ip is invalid
if ip == nil{
view.setSeriesSyncCompleted()
view.setTemplateSyncCompleted()
view.setInspectionSyncCompleted()
view.completion("Error: Failed to connect to ***, please reset connection")
}
//Call the inspection sync function.
syncInspections(ip, view: view)
}
//Function to respond to authentication challenges.
func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) {
let credential = NSURLCredential(user: "MAMA", password: "PassWord", persistence: .ForSession)
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, credential)
}
はい、それは問題なく動作します。22 秒で 280 以上のファイル (.json と .jpg) をダウンロードできます。
そして、計画はそれ以上のものを手に入れることです..だから私はこれをより速く行う方法が本当に必要です.
必要に応じて、使用しているコードをさらに提供できます。
前もって感謝します :)