网络请求失败

时间:2016-07-03 10:56:37

标签: xcode swift networking

我刚刚开始迅速,我正试图发布这样的帖子请求:

import UIKit

class ViewController: UIViewController {


    @IBOutlet var txtEmail: UITextField!
    @IBOutlet var txtPassword: UITextField!
    @IBOutlet var btnLogin: UIButton!


    override func viewDidLoad() {
        super.viewDidLoad()
    }

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


    @IBAction func btnSignIn(sender: AnyObject) {
        let session = NSURLSession.sharedSession()
        let url = NSURL(string: "http://temp.com/api/v1/login")!
        let request = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"
        let task = session.dataTaskWithRequest(request) {
            (data, response, error) in
            guard let data = data else {print(error); return}

            let result = NSString(data: data, encoding: NSUTF8StringEncoding)
            print(result)

        }
        task.resume()
    }

}

当我在Xcode中启动我的模拟器时,它会显示build succeeded,然后它会崩溃:

class AppDelegate:

消息:

Thread 1: signal SIGABRT

我做错了什么?当我在操场上测试时,它可以工作!

1 个答案:

答案 0 :(得分:0)

看起来它在AppDelegate中崩溃,没有看到那里的代码,我无法准确地告诉你问题是什么。

如果删除btnSignIn方法中的代码,它是否仍会崩溃?

我通常会这样处理我的POST请求:

let session = NSURLSession.sharedSession()
let url = NSURL(string: urlString)
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"

// fill the request body, my API accepts JSON params
if let jsonData = try? NSJSONSerialization.dataWithJSONObject(parameters, options: .PrettyPrinted) {
    request.HTTPBody = jsonData
} else {
    print("error sending params as JSON, params: \(parameters)")
}

let task = session.dataTaskWithRequest(request) { (data, response, error) in
    self.handleResponse(request, data: data, response: response, error: error, completionHandler: completionHandler)
}

task.resume()