Swift: NSURLSession taskからJSON string を返す

投稿者: Anonymous

JSON データから token を String 形式で取り出したいです。しかし以下のコードでは、""Use of unresolved identifier "tokenString". というエラーが生じ取り出すことが出来ません。解決策を教えてください。

func authentication() -> String {
    let request = NSMutableURLRequest(URL: NSURL(string: "https://~~~/v2/authenticate/api")!)
    request.HTTPMethod = "POST"

    var loginID = "my_ID"
    var apiKey = "my_APIKEY"
    var postString:NSString = "login_id=(loginID)&api_key=(apiKey)"

    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        if error != nil {
            println("error=(error)")
            return
        }

        println("response = (response)")

        let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("responseString = (responseString)")


        let json = JSON(data:data)
        if let token = json["auth_token"].stringValue{
            println("(token)")

            tokenString = self.didReceiveAuthToken(token)///Edited 
        }
    }
    task.resume()
    return tokenString
}
func didReceiveAuthToken(token : String) ->String{
    return token
}

解決

以下のようにすることで解決致しました。

var tokenString : String = ""  
func authentication(){
    let request = NSMutableURLRequest(URL: NSURL(string: "https://~~~/v2/authenticate/api")!)
    request.HTTPMethod = "POST"

    var loginID = "my_ID"
    var apiKey = "my_KEY"
    var postString:NSString = "login_id=(loginID)&api_key=(apiKey)"

    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        if error != nil {
            println("error=(error)")
            return
        }

        println("response = (response)")

        let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("responseString = (responseString)")


        let json = JSON(data:data)
        if let token = json["auth_token"].stringValue{
            println("(token)")
            self.didReceiveAuthToken(token)
        }

    }
    task.resume()
}

func didReceiveAuthToken(token : String){
    tokenString = token
}
回答者: Anonymous

Leave a Reply

Your email address will not be published. Required fields are marked *