LoginSignup
29
31

More than 5 years have passed since last update.

NSURLSessionで同期通信

Last updated at Posted at 2016-01-12

同期通信の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
*/

参考

29
31
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
31