调整Swift代码以使用Swift 3

时间:2016-11-11 09:13:31

标签: swift xcode swift3

我是Swift和XCode的新手,但是现在就试着看看我是怎么过的。

无论如何,我已经从this post通过Belal Khan查看了一些代码,将手机应用程序连接到MySQL数据库。它似乎需要更新才能使用最新版本的Swift。

我认为我已经完成了大部分工作,但是我更新了一个特定的部分。

//
//  ViewController.swift
//  SwiftPHPMySQL
//
//  Created by Belal Khan on 12/08/16.
//  Copyright © 2016 Belal Khan. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    //URL to our web service
    let URL_SAVE_TEAM = "http://www.example.com/api/createteam.php"


    //TextFields declarations
    @IBOutlet weak var textFieldName: UITextField!
    @IBOutlet weak var textFieldMember: UITextField!



    //Button action method
    @IBAction func buttonSave(sender: UIButton) {

        //created NSURL
        let requestURL = NSURL(string: URL_SAVE_TEAM)

        //creating NSMutableURLRequest
        let request = NSMutableURLRequest(URL: requestURL!)

        //setting the method to post
        request.HTTPMethod = "POST"

        //getting values from text fields
        let teamName=textFieldName.text
        let memberCount = textFieldMember.text

        //creating the post parameter by concatenating the keys and values from text field
        let postParameters = "name="+teamName!+"&member="+memberCount!;

        //adding the parameters to request body
        request.HTTPBody = postParameters.dataUsingEncoding(NSUTF8StringEncoding)


        //creating a task to send the post request
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
            data, response, error in

            if error != nil{
                print("error is \(error)")
                return;
            }

            //parsing the response
            do {
                //converting resonse to NSDictionary
                let myJSON =  try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

                //parsing the json
                if let parseJSON = myJSON {

                    //creating a string
                    var msg : String!

                    //getting the json response
                    msg = parseJSON["message"] as! String?

                    //printing the response
                    print(msg)

                }
            } catch {
                print(error)
            }

        }
        //executing the task
        task.resume()

    }


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

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

这就是我到目前为止更新它...

//
//  ViewController.swift
//  SwiftPHPMySQL
//
//  Created by Belal Khan on 12/08/16.
//  Copyright © 2016 Belal Khan. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    //URL to our web service
    let URL_SAVE_TEAM = "http://www.example.com/api/createteam.php"


    //TextFields declarations
    @IBOutlet weak var textFieldName: UITextField!
    @IBOutlet weak var textFieldMember: UITextField!



    //Button action method
    @IBAction func buttonSave(sender: UIButton) {

        //created NSURL
        let requestURL = URL(string: URL_SAVE_TEAM)

        //creating NSMutableURLRequest
        let request = NSMutableURLRequest(url: requestURL!)

        //setting the method to post
        request.httpMethod = "POST"

        //getting values from text fields
        let teamName=textFieldName.text
        let memberCount = textFieldMember.text

        //creating the post parameter by concatenating the keys and values from text field
        let postParameters = "name="+teamName!+"&member="+memberCount!;

        //adding the parameters to request body
        request.httpBody = postParameters.data(using: .utf8)


        //creating a task to send the post request
        let task = URLSession.sharedSession().dataTaskWithRequest(request){
            data, response, error in

            if error != nil{
                print("error is \(error)")
                return;
            }

            //parsing the response
            do {
                //converting resonse to NSDictionary
                let myJSON =  try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

                //parsing the json
                if let parseJSON = myJSON {

                    //creating a string
                    var msg : String!

                    //getting the json response
                    msg = parseJSON["message"] as! String?

                    //printing the response
                    print(msg)

                }
            } catch {
                print(error)
            }

        }
        //executing the task
        task.resume()

    }


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

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

错误在线:

let task = URLSession.sharedSession().dataTaskWithRequest(request){

我得到的错误是Cannot call value of non-function type 'URLSession'

2 个答案:

答案 0 :(得分:0)

将其更改为此

 URLSession.shared.dataTask(with: request, completionHandler: {data, response, error in
    ...
     })

答案 1 :(得分:0)

您正在创建 NSMutableURLRequest 请求,但是,URLSession需要 URLRequest

let request = URLRequest(url: NSURL(string: "") as! URL)

URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
   if error == nil {
     print("Seccess")
   } else {
     print("Error")
   }
}

感谢:)