-1

我目前正在尝试使用 Swift 以 JSON 格式从 mySQL 中检索数据。我意识到NSURL已更改为URL. 我正在遵循另一个较旧的代码来帮助指导我完成这个,但它已经过时了。我在let request和处有错误(NSURL/URL) let task。我需要一些帮助来弄清楚如何正确地做到这一点。谢谢!

   override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        //********************************************************************
        //MySQL Url Request
        let URLRequest = NSURL(string: URLWarrick)
        //Creating mutable request
        let request = NSMutableURLRequest(url: URLRequest!)
        //setting method to post
        request.httpMethod = "GET"
        //Task to send request

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
            data, response, error in

            //exiting if there is some error
            if error != nil{
                print("error is \(error)")
                return;
            }

            do {
                //converting response to NSDictionary
                var teamJSON: NSDictionary!
                WarrickJSON =  try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

                //getting the JSON array teams from the response
                //let teams: NSArray = teamJSON["teams"] as! NSArray

                //looping through all the json objects in the array teams
                //for i in 0 ..< teams.count{

                    //getting the data at each index
                    //let teamId:Int = teams[i]["id"] as! Int!
                    //let teamName:String = teams[i]["name"] as! String!
                    //let teamMember:Int = teams[i]["member"] as! Int!

                    //displaying the data
                    //print("id -> ", teamId)
                    //print("name -> ", teamName)
                    //print("member -> ", teamMember)
                    //print("===================")
                    //print("")

                }
4

2 回答 2

0

您非常接近正确的格式。为了在 Swift 3 中正确,它应该如下所示:

if let let url = URL(string: URLWarrick) {
    var request = URLRequest(url: url)
    request.httpMethod = "GET"
    var session: URLSession = URLSession.shared
    let task = session.dataTask(with: request) { (data, response, error) -> Void in
         // Your completion handler code goes here
    }
    task.resume()
}

最大的变化是在 swift 3 中你不再需要一个可变的 url 请求,它现在作为一个 var 被正确处理。然后您现在使用 URLSession 发送该请求。

于 2017-05-24T20:53:39.460 回答
0

这是 URL 请求的典型结构。GETrequest 是默认设置,因此您不需要NSMutableURLRequest指定它。

if let url = URL(string: URLWarrick) {

    let request = URLRequest(url: url)

    let session = URLSession.shared

    let task = session.dataTask(with: request, completionHandler: { (data, response, error) in

        if let error = error {

            print(error.localizedDescription)

            return
        }

        if let data = data {

            if let json = try? JSONSerialization.jsonObject(with: data) {

                if let dict = json as? Dictionary<String,Any> {

                    if let teams = dict["teams"] as? Array<Dictionary<String,Any>> {

                        for team in teams {

                            guard

                                let id = team["id"] as? Int,

                                let name = team["name"] as? String,

                                let member = team["memeber"] as? Int

                            else {

                                print("Error! - Data for this team is incomplete.")

                                continue
                            }

                            print(id, name, member)
                        }

                        return
                    }
                }
            }
        }

        print("Error! - Your data was invalid.")
    })

    task.resume()
}
于 2017-05-24T20:54:00.543 回答