0

您好,我正在尝试从我的服务器发出 get 请求,但是当我检查了我的日志并且我什至没有到达最终端点时,我未能到达端点。端点需要已添加到请求字段的授权。我正在尝试获取 json 值并将它们显示为表格单元格。但是当我尝试检索它返回 nil 的值时。它从不尝试到达端点。我试图放置一个打印语句print("Session)"来检查它是否调用 dataWithRequest 但如果没有这样做。请问我在这里做错什么了吗?

 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
   }
}
4

1 回答 1

1

让这些东西添加到你的 Info.plist 在此处输入图像描述

更新:让我们使用完成处理程序而不是返回一个值

func getLocalData(completion: (json: [[String:AnyObject]]?) -> Void) {
    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("", 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)")
            completion(json: nil)
            return
        }

        let httpResponse = response as! NSHTTPURLResponse//HTTPURLResponse
        let statusCode = httpResponse.statusCode

        if statusCode == 200 {
            do {
                print("Here buddy")
                let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [[String: AnyObject]]
                // return json
                completion(json: json)
            }

            catch {
                print("Error in json")
                completion(json: nil)
            }
        }
    }

    task.resume()
}

和:

myDeals.getLocalData { json in
    print("json: \(json)")
    dealsArray = json!
}
于 2016-11-06T02:51:55.520 回答