【问题标题】:HTTP request in swift 3 Xcode 8.3swift 3 Xcode 8.3中的HTTP请求
【发布时间】:2017-04-14 11:03:00
【问题描述】:

我遇到了 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()
}

【问题讨论】:

  • 这很明显,因为dataTask 的完成块将在您收到响应后调用
  • 问题是什么?
  • 它造成了什么问题?
  • @ch umer 解决了您的问题?
  • @NiravD 谢谢你的回答其实我是新来的 swift

标签: ios swift swift3


【解决方案1】:

使用块 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"

【讨论】:

  • 对于 GET 请求,不需要显式的 URLRequest,在 Swift 3 中使用本机 URLRequest 而不是 NSMutableURLRequest
  • 感谢您分享您的知识。我的意思是他错过了请求httpMethod。
  • 基本上问题中的代码工作,GET是默认的。
猜你喜欢
  • 1970-01-01
  • 2017-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多