2015-10-05 79 views
0

我在swift 2.0項目中使用了下面的代碼。儘管我添加了「導入Alamofire」,但我無法添加Alamofire.request。我必須創建Alamofire的對象,然後通過它訪問。swift中的Alomofire POST請求

這是我如何創建對象:

let manager = Alamofire.Manager.sharedInstance 
manager.request(NSURLRequest(URL: NSURL(string: "http://httpbin.org/get")!)) 

let parameters = ["foo": "bar"] 

manager.request(.POST, "url", parameters: parameters) 
.responseJSON { request, response, json, error in 
print("request: \(request)") 
} 

我是新來的都Alamofire快捷。任何人都可以告訴我如何在完成處理程序中獲得上述代碼的響應,以及爲什麼我不能使用Alamofire.request而不是使用manager.request。

回答

2

請求並不總是JSON請檢查您的要求:

示例如下使用Alamofire與斯威夫特2:

GET - JSON

Alamofire.request(.GET, "http://api.androidhive.info/contacts/", parameters: nil, encoding: .JSON, headers: nil).responseJSON { (req, res, json) -> Void in 
    print("\(res?.allHeaderFields)") 
    print("\(json.value!)") 
} 

POST - 沒有JSON

Alamofire.request(.POST, "http://httpbin.org/get", parameters: ["foo": "bar"], encoding: .URL, headers: nil).response { (req, res, data, error) -> Void in 
    print(res) 
    print(data) 

    let dataString = NSString(data: data!, encoding:NSUTF8StringEncoding) 
    print(dataString) 
} 
+0

謝謝哥哥。你的代碼對我來說非常完美。你能不能讓我知道爲什麼我不能在我的xcode中自動完成Alomofire.request,但是如果我複製你的代碼,我沒有收到任何錯誤。爲了自動完成,我必須添加一個Alomofire對象,然後繼續。 –

+0

你已經創建了Alamofire的實例,並且你已經創建了一個URL請求,不需要這樣做。 Alamofire會照顧它。保持它@ user3730935 –

+0

但沒有,我不能自動完成我的編碼! :( –

4

請參閱我的文章的方法和希望它可以幫助

POST方法:

/** 
    ** POST Method for calling API 
    * Services gateway 
    * Method get response from server 
    * @parameter    -> requestObject: request josn object ,apiName: api endpoint 
    * @returm     -> void 
    * @compilationHandler  -> success: status of api, response: respose from server, error: error handling 
    **/ 
    static func getDataWithObject(requestObject: NSDictionary, apiName : NSString, 
     completionHandler: 
     (success : Bool, response : NSDictionary, error : ErrorType?) -> Void) { 

      // Make Url 
      let url = NSURL(string: apiName as String) 
      let request = NSMutableURLRequest(URL: url!) 
      request.HTTPMethod = "POST" 
      //request.setValue("application/json", forHTTPHeaderField: "Content-Type") 

      // Call the method to request and wait for the response 
      // @param -> 
      // @return -> 
      Alamofire.request(.POST, url!, parameters:requestObject as? [String : AnyObject], encoding: .JSON) 
       .responseJSON {responseRequest, responseResponse, responseResult in 

        // Switch for Success or Error 
        switch responseResult { 

         // If the API return succesfull response 
        case .Success(let data): 

         let data_ar = data as! NSDictionary 
         print(data_ar) 
         // Get the Status if 0 then error if 1 then succes 
         // From our server side 
         if let str = data_ar.valueForKey("OK") as? Bool { 

          // Check if the status is OK and no error from 
          // our server side 
          if (str) { 

           print("Response from Server %@", data_ar) 

           // Cast the response and pss to handler 
           // To notify 
           completionHandler(success: true, response:data_ar 
            , error:responseResult.error) 
          } else { 
           print("Error from Our Server %@", data_ar) 
           let str = data_ar.valueForKey("message") as! NSString 
           self.showAlertView(str, title: "Error From Server") 
          } 

         } 

        case .Failure(let data, let error): 
         print("Request failed with error: \(error)") 
         print(data) 
         print((error as! NSError).localizedDescription) 
         self.showAlertView((error as! NSError).localizedDescription, title: "Error From Server") 

        } 
      } 
    } 
+0

不錯的工作Raheel! –