在swift中发出GET请求时无法命中端点

时间:2016-11-06 02:23:58

标签: ios swift2.3

您好我正在尝试从我的服务器发出一个get请求但是我没有点击端点,因为我检查了我的日志,甚至没有达到最终端点。端点需要已添加到请求字段的授权。我试图获取json值并将它们显示为表格单元格。但是当我尝试检索值时,它返回nil。它永远不会尝试命中端点。我试图放置一个print语句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
   }
}

1 个答案:

答案 0 :(得分:1)

将这些内容添加到Info.plist中 enter image description here

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

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