我的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))
}
但是我收到错误:' ViewController.Type'没有名为' URL'的成员。如果我将代码放在ViewDidLoad中,它适用于应用程序启动。
如何通过点击按钮运行代码?我尝试将@IBAction放在ViewDidLoad函数中,但这也不起作用:/
编辑:完整视图
//
// 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.
}
}
答案 0 :(得分:3)
您的所有代码都不在方法中,将其包装在方法中并在适当时调用该方法。