我怎样才能从NSUrlSession返回一个NSHttpUrlResponse状态代码。 我对这种语言很陌生。所以,如果还有其他更好的做法,请告诉我。我的代码就在这里。我怎样才能返回从NSUrlSession的NSHttpUrlResponse状态代码
//Method to return a status code
func responseCode() -> Int{
var responseCode : Int=0
if Reachability.isConnectedToNetwork() == true {
// get news feed url
let url = NSURL(string: baseUrl)
let session = NSURLSession.sharedSession()
//create request
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = httpMethod
//check null value
if (bodyData != "") {
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
}
if (auth != "") {
print("Token Auth : \(auth)")
request.addValue("bearer \(self.auth)", forHTTPHeaderField: "Authorization")
}
print("request : \(request)")
//How to return a Integer from this below function
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) -> Void in
print("Error\(error)")
if let httpResponse = response as? NSHTTPURLResponse {
print("HttpReponse\(httpResponse.statusCode)")
// Get a status code and assign it in a variable
responseCode = httpResponse.statusCode
}
})
task.resume()
//Return a response code in ViewController but it just return a initial set value that is 0
return responseCode
}
//Return a responseCode in ViewController but it just return a initial set value that is 0
return responseCode
}
我有看到这个以前而是因为我很新的语言无法理解了。你可以请编辑我的代码。 – user3797004