2015-07-20 64 views
3

我在我的應用程序中登錄頁面,在該頁面中進行身份驗證併發出發布請求。 我將從API提供的API中獲取令牌。 但是,我的代碼沒有在打印日誌上打印任何內容。請幫忙!!如何在Swift中創建'post'HTTP請求?

@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() 

     } 

回答

1

幾個問題:

  1. 首先,您同時使用NSURLConnectionNSURLSession。這意味着你實際上執行了兩次請求。現在,NSURLConnection即將被棄用,您應該刪除此代碼段的NSURLConnection部分,並使用NSURLSession。其次,在解析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 
    } 
    

通常這些類型的請求,因爲一些錯誤的原始NSURLRequest是如何創建的失敗,但你是不是向我們展示的足夠的信息源問題。

+0

太棒了!我接受了你的建議,並且它工作正常 – user2832411

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() 

     }