その中でも一番大きかったのがjsonの取得に使っていたsendAsynchronousRequestがdeprecatedになっていた事でした。
今まではこんな感じ。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//★★★★★★★★★★★★★★★★★★ | |
// APIへの問い合わせ | |
func getJson() { | |
let URL = NSURL(string: "APIのURL") | |
let req = NSURLRequest(URL: URL!) | |
NSURLConnection.sendAsynchronousRequest(req, | |
queue: NSOperationQueue.mainQueue(), | |
completionHandler: responseJson) | |
} | |
//★★★★★★★★★★★★★★★★★★ | |
// 取得したAPIデータの処理 | |
func responseJson(res: NSURLResponse?, data: NSData?, error: NSError?){ | |
if (error == nil) && (data != nil){ | |
let json: AnyObject! = (try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)) as? NSArray | |
} else { | |
//エラー処理 | |
} | |
} |
18行目のjsonにデータが格納されるので、取り出して使っていました。
swift2ではNSURLSessionのdataTaskWithRequestを使えと怒られます。。。
swift2から下記の通りで同様に問合せ出来ました。
NSURLSessionのdataTaskWithRequestでリクエストを作り、do try catchで処理するのがポイント。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func getJson() { | |
let URL = NSURL(string: "APIのURL") | |
let req = NSURLRequest(URL: URL!) | |
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() | |
let session = NSURLSession(configuration: configuration, delegate:nil, delegateQueue:NSOperationQueue.mainQueue()) | |
let task = session.dataTaskWithRequest(req, completionHandler: { | |
(data, response, error) -> Void in | |
do { | |
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.AllowFragments ) as! NSArray | |
} catch { | |
//エラー処理 | |
} | |
}) | |
task.resume() | |
} |
0 コメント:
コメントを投稿