如何通过NSURLConnection接收数据?

时间:2014-12-25 02:21:02

标签: php ios swift nsurlconnection

我正在使用一个使用PHP Web服务查询数据库的Swift应用程序。一个问题 - 我不知道如何判断模型类中何时收到数据,因此我无法更新视图!如何判断连接是否已完成,然后更新所述视图?为此,我创建了一个名为text的虚拟标签。感谢提前帮助,节日快乐!

User.swift

import Foundation

class User: NSObject {

    var firstName: String?
    var lastName: String?
    var username: String
    var password: String
    var email: String?

    var recievedJSON: NSMutableData = NSMutableData()
    var userData: [[String: String]]!

    var verified: Bool = false

    required init(username: String, password: String) {
        self.username = username
        self.password = password
    }

    init(firstName: String, lastName: String, username: String, password: String, email: String) {
        self.firstName = firstName
        self.lastName = lastName
        self.username = username
        self.password = password
        self.email = email
    }

    func attemptRegister() {
        var variables: [String] = ["firstname=" + self.firstName! + "&"]
        variables.append("lastname=" + self.lastName! + "&")
        variables.append("username=" + self.username + "&")
        variables.append("password=" + self.password + "&")
        variables.append("email=" + self.email!)
        request("https://codekaufman.com/register.php", variables: variables)
    }

    func attemptSignIn() {
        var variables: [String] = ["username=" + self.username + "&"]
        variables.append("password=" + self.password)
        request("https://codekaufman.com/login.php", variables: variables)
        println("Attempting sign-in...")
    }

    private func request(urlPath: String, variables: [String]?) {
        var url: NSURL = NSURL(string: urlPath)!
        var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)

        if(variables != nil) {
            request.HTTPMethod = "POST"

            var bodyData: NSString = ""
            for item in variables! {
                bodyData = bodyData + NSString(string: item)
            }

            request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)
        }

        var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
        connection.start()
        println("Connection started.")
    }

    func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
        self.recievedJSON.appendData(data)
        println("Possible data recieved.")
    }

    func connectionDidFinishLoading(connection: NSURLConnection!) {
        userData = parseJSON(recievedJSON)

        if(userData != nil) {
            println("Data recieved:")
            println(userData[0])
            self.firstName = userData[0]["first_name"]
            self.lastName = userData[0]["last_name"]
        } else {
            println("No data recieved.")
        }

    }

    func parseJSON(inputData: NSData) -> [[String: String]]? {
        var error: NSError?
        var userData: [[String: String]]!
        userData = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as? [[String: String]]

        #if DEBUG

        if (userData != nil) {
            println("NSData had data, printing and returning.")
            println(userData)
        } else {
            println("NSData empty, returning nil.")
        }

        #endif

        return userData
    }

}

ViewController.swift

import UIKit

class ViewController: UIViewController {

    @IBAction func prepareForUnwind(seque: UIStoryboardSegue) {

    }

    @IBOutlet weak var username: UITextField!
    @IBOutlet weak var password: UITextField!
    @IBOutlet weak var text: UILabel!

    @IBAction func signin(sender: AnyObject) {
        if(username.text == "" || password.text == "") {
            var alert = UIAlertController(title: "Error", message: "Invalid Credentials", preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
        } else {
            var attempt: User = User(username: username.text, password: password.text)
            attempt.attemptSignIn()
        }

    }

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }

}

编辑:根据以前的评论/答案,我觉得我应该澄清一下。正在收到数据。但它需要几秒钟,那么我如何向视图控制器表明已收到数据,并且该过程已完成?

1 个答案:

答案 0 :(得分:0)

您可以在视图控制器中添加通知:

func addObserverForName(_ name: String?, object obj: AnyObject?, queue queue: NSOperationQueue?, usingBlock block: (NSNotification!) -> Void) -> NSObjectProtocol

请务必将其删除:

func removeObserver(_ notificationObserver: AnyObject)

使用以下方式从connectionDidFinishLoading发送通知

func postNotificationName(_ notificationName: String, object notificationSender: AnyObject?, userInfo userInfo: [NSObject : AnyObject]?)