同期通信のNSURLConnection.sendSynchronousRequestメソッドがiOS9.0にて非推奨で、"Use [NSURLSession dataTaskWithRequest:completionHandler:] (see NSURLSession.h"になっていた。
なので、NSURLSession.dataTaskWithRequestメソッドを利用した同期通信の実装を行うことにした。
実装方法
以下はplaygroundで記載。
SyncPlaygound.playground
func sendSynchronize(urlPath:String, completion: (NSData?, NSURLResponse?, NSError?) -> Void) {
let semaphore = dispatch_semaphore_create(0)
let url: NSURL = NSURL(string: urlPath)!
let request: NSURLRequest = NSURLRequest(URL: url)
let subtask = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { data, res, error in
completion(data, res, error)
dispatch_semaphore_signal(semaphore)
})
subtask.resume()
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
}
let urlPath: String = "http://(テスト用のURL)"
for i in 0...1000 {
print("\(i)Start")
sendSynchronize(urlPath, completion:{ data, res, error in
print("\(i)completion")
})
print("\(i)end")
}
/*実行結果
0Start
0completion
0end
1Start
1completion
1end
2Start
2completion
2end
・
・
・
999Start
999completion
999end
1000Start
1000completion
1000end
*/