您好,我正在嘗試從我的服務器發出get請求,但由於我檢查了日誌並且即使沒有擊中最終端點,我也無法擊中端點。端點需要已經添加到請求字段的授權。我試圖獲取json值並將它們顯示爲表格單元格。但是,當我試圖檢索值返回零。它從不嘗試擊中端點。我試圖把打印語句print("Session)"
檢查它是否調用dataWithRequest,但是如果不能這樣做。請問我在這裏做錯了什麼?無法在swift中發出GET請求時觸發終端
func getLocalData() -> [[String:AnyObject]] {
var json:[[String:AnyObject]]?
let endPoint = "http://******************"
let url:NSURL? = NSURL(string: endPoint)
let session = NSURLSession.sharedSession()
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue(token!, forHTTPHeaderField: "Authorization-Header")
let task = session.dataTaskWithRequest(request) {(data, response, error) -> Void in
print("Session") //not able to get in here
guard let data = data where error == nil else {
//network error
print("Error with network: \(error?.localizedDescription)")
return
}
let httpResponse = response as! NSHTTPURLResponse//HTTPURLResponse
let statusCode = httpResponse.statusCode
if statusCode == 200 {
do {
print("Here buddy")
json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [[String: AnyObject]]
// return json
}
catch {
print("Error in json")
}
}
}
task.resume()
print("JSON: \(json)") //prints nil as it never attempts to make the request to the server
return json
}
,並在我的TableListController我試圖調用此函數,它抱怨的fatal error: unexpectedly found nil while unwrapping an Optional value
class DealListController: UITableViewController {
let myDeals = DealList()
var dealsArray = []
override func awakeFromNib() {
super.awakeFromNib()
dealsArray = myDeals.getLocalData()! //complains about error here
}
}
您的端點是http://或https://? –
@DanhHuynh http。我部署服務器上的heroku – user3497437