Swift: 'ViewController.Type' does not have

2019-07-27 13:45发布

问题:

I have some code in my viewController

 var URL: NSURL = NSURL(string: "http://someurl.com")!
 var request : NSMutableURLRequest = NSMutableURLRequest(URL:URL)

 request.HTTPMethod = "POST"

 var bodyData = "data=something"


 NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
    {
        (response, data, error) in
        println(NSString(data: data, encoding: NSUTF8StringEncoding))
    }

However I get the error: 'ViewController.Type' does not have a member named 'URL'. If I put the code in the ViewDidLoad it works on app launch.

How do I get the code to run on the click of a button? I tried putting the @IBAction in the ViewDidLoad func but that doesnt work either :/

edit: Full View

 //
 //  ViewController.swift
 //  postPhp
 //
 //  Created by  -  on 01/12/2014.
 //  Copyright (c) 2014 Dannie C. All rights reserved.
 //

 import UIKit

 class ViewController: UIViewController {


 var URL: NSURL = NSURL(string: "http://someurl.com")!
 var request : NSMutableURLRequest = NSMutableURLRequest(URL:URL)

 request.HTTPMethod = "POST"

 var bodyData = "data=something"


 NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
  {
   (response, data, error) in
   println(NSString(data: data, encoding: NSUTF8StringEncoding))
  }



@IBOutlet var serverLabel: UILabel!

@IBAction func serverButton(sender: AnyObject) {


}


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.
}

}

回答1:

None of your code is in a method, wrap it up in a method and call the method when appropriate.