mysqljsonswiftxcodeswiftcharts

swift NSURL changes swift 3.1


I am currently attempting to retrieve data from mySQL with Swift in JSON format. I realize that NSURL has been changed to URL. I am following another older code to help guide me through this but it is out of date. I have errors (NSURL/URL) at let request and let task. I need some help sorting out how to do this correctly. Thank you!

   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("")

                }

Solution

  • This is a typical structure of a URL request. GET request is the default, so you don't need to have a NSMutableURLRequest to specify that.

    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()
    }