我被HTTP请求卡住了。它没有显示任何错误。编译器读取了前两行,并将代码跳过到“task.resume()”。我在其他视图控制器上以相同的代码获取数据,但是这在这里造成了问题

func getCustomers()
{
    let url = NSURL(string: "myURL.com")
    let task = URLSession.shared.dataTask(with: url! as URL) {
        (data, response, error) in

        guard let _:Data = data, let _:URLResponse = response  , error == nil else {
            print("error: \(String(describing: error))")

            return
        }
        do
        {
            self.getcustomersArray = [GetCustomers]()
            //JSON Parsing
            if let data = data,

                let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]
            {
                let results = json["Result"] as? [[String : Any]]

                let getCustomersObject:GetCustomers = GetCustomers()
                for result in results!
                {
                    getCustomersObject.ActivityPrefix = (result["ActivityPrefix"] as? String)!
                    getCustomersObject.CustomerID = (result["CustomerID"] as? String)!
                    getCustomersObject.CustomerName = (result["CustomerName"] as? String)!
                    getCustomersObject.TFMCustomerID = (result["TFMCustomerID"] as? String)!
                    getCustomersObject.ShortName = (result["ShortName"] as? String)!
                    getCustomersObject.UserRights = (result["UserRights"] as? Int)!

                    self.totalCustomers += self.totalCustomers
                }
                self.customerName = getCustomersObject.CustomerName

            }
        }//end Do
        catch
        {

        }
    }

    task.resume()
}

最佳答案

使用块GET / POST / PUT / DELETE:

 let request = NSMutableURLRequest(url: URL(string: "Your API URL here" ,param: param))!,
        cachePolicy: .useProtocolCachePolicy,
        timeoutInterval:"Your request timeout time in Seconds")
    request.httpMethod = "GET"
    request.allHTTPHeaderFields = headers as? [String : String]

    let session = URLSession.shared

    let dataTask = session.dataTask(with: request as URLRequest) {data,response,error in
        let httpResponse = response as? HTTPURLResponse

        if (error != nil) {
         print(error)
         } else {
         print(httpResponse)
         }

        DispatchQueue.main.async {
           //Update your UI here
        }

    }
    dataTask.resume()

我想你不提线
request.httpMethod =“GET”

关于ios - Swift 3 Xcode 8.3中的HTTP请求,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43410253/

10-13 21:43