如何在Swift中发布'发布'HTTP请求?

时间:2015-07-20 20:26:30

标签: swift authentication

我在我的应用中有一个登录页面,我正在进行身份验证并发布帖子请求。 我将从我提供的API中获取令牌。 但是,我的代码不会在打印日志上打印任何内容。请帮忙!!

    @IBAction func submit(sender: AnyObject) {  

//creating a function that will connect to API  


        func connectToWebAPI(){  

//setting up the base64-encoded credentials  
        let userName = "user"  
        let password = "pass"  
        let loginString = NSString(format: "%@:%@", userName, password)  
        let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!  
        let base64LoginString = loginData.base64EncodedStringWithOptions(nil)  

//creating the request  
        let url = NSURL(string: "http://www.telize.com/geoip") 
        var request = NSMutableURLRequest(URL: url!)  
        let config = NSURLSessionConfiguration.defaultSessionConfiguration()  
        let session = NSURLSession.sharedSession()  
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")  
        request.addValue("application/json", forHTTPHeaderField: "Accept")  

        let urlConnection = NSURLConnection(request: request, delegate: self)  
        request.HTTPMethod = "POST"  
        request.setValue(base64LoginString, forHTTPHeaderField: "Authorization")  


        let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in  
        if (error != nil) {  
                    println(error)  

        }  
        else {  

// converting the data into Dictionary  

        let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary  

        println(jsonResult)  

                }  
            })  


//fire off the request  

        task.resume()  

        }  

2 个答案:

答案 0 :(得分:1)

有几个问题:

  1. 首先,您同时使用NSURLConnectionNSURLSession。这意味着您实际执行了两次请求。现在,在NSURLConnection即将被弃用的情况下,您应该删除此代码段的NSURLConnection部分并仅使用NSURLSession

  2. 其次,在解析JSON时,您明确告诉它不报告任何错误(您将error参数设置为nil)。你应该看看错误,如果有的话:

    var parseError: NSError?
    if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &parseError) as? NSDictionary {
        println("jsonResult = \(jsonResult)")  
    } else { 
        // if it didn't work, show enough so we can figure out why:
    
        println("parseError = \(parseError)")
        println("response = \(response)")
        let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("responseString = \(responseString)") // this will probably be HTML from the server describing some problem in the request
    }
    
  3. 通常这些请求会因原始NSURLRequest的创建方式出现问题而失败,但您没有向我们展示问题的足够信息来源。

答案 1 :(得分:1)

这是寻找答案的任何人的最终代码。

//setting up the base64-encoded credentials
        let userName = "user"
        let password = "pass"
        let loginString = NSString(format: "%@:%@", userName, password)
        let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
        let base64LoginString = loginData.base64EncodedStringWithOptions(nil)

//creating the request 
        let url = NSURL(string: "http://www.telize.com/geoip")
        var request = NSMutableURLRequest(URL: url!)
        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession.sharedSession()
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        request.HTTPMethod = "POST"
        request.setValue(base64LoginString, forHTTPHeaderField: "Authorization")


        let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in


            var parseError: NSError?

        if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &parseError) as? NSDictionary {
        println("jsonResult = \(jsonResult)")

        }
        else {
        //if this didn't work, show enough so we can figure out why:
            println("parseError = \(parseError)")
            println("response = \(response)")
            let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
            println("responseString = \(responseString)")

            }
            })


//fire off the request

        task.resume()

        }