【问题标题】:Get JSON result with GET request and parameters with Alamofire使用 GET 请求获取 JSON 结果并使用 Alamofire 获取参数
【发布时间】:2016-08-07 01:52:27
【问题描述】:

这是我的带参数的 url 字符串。 http://api.room2shop.com/api/product/GetProducts?categoryId=22&filter=2&pageNumber=1 通过它获取我的 JSON 数据。我有 AFWrapper.swift 文件,其中我为 GETrequest 定义了函数。

import UIKit
import Alamofire
import SwiftyJSON

class AFWrapper: NSObject {

    class func requestGETURL(strURL: String, params : [String : AnyObject]?, success:(JSON) -> Void, failure:(NSError) -> Void) {
        Alamofire.request(.GET, strURL, parameters: params, encoding: ParameterEncoding.JSON).responseJSON { (responseObject) -> Void in

            print(responseObject)

            if responseObject.result.isSuccess {
                let resJson = JSON(responseObject.result.value!)
                success(resJson)
            }
            if responseObject.result.isFailure {
                let error : NSError = responseObject.result.error!
                failure(error)
            }


           }
        }
}

现在我在我的 ViewController.swift 文件中调用这个函数。

let strURL = "http://api.room2shop.com/api/product/GetProducts"
    let param = ["categoryId": "22", "filter": "2", "pageNumber": "1"]
    AFWrapper.requestGETURL(strURL, params: param, success: {
        (JSONResponse) -> Void in

        if let resData = JSONResponse["ProductList"].arrayObject {
            for item in resData {
                self.TableData.append(datastruct(add: item as! NSDictionary))
            }

        do
        {
            try self.read()
        }
        catch
        {
        }
        self.do_table_refresh()
    }

}) {
    (error) -> Void in
    print(error)
}

但它没有给我任何回应并给我这个错误。

FAILURE: Error Domain=NSURLErrorDomain Code=-1017 "无法解析 回复” UserInfo={NSErrorFailingURLStringKey=http://api.room2shop.com/api/product/GetProducts, _kCFStreamErrorCodeKey=-1, NSErrorFailingURLKey=http://api.room2shop.com/api/product/GetProducts, NSLocalizedDescription=无法解析响应, _kCFStreamErrorDomainKey=4, NSUnderlyingError=0x78ecf180 {错误域=kCFErrorDomainCFNetwork 代码=-1017 "(null)" UserInfo={_kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-1}}} 错误域=NSURLErrorDomain 代码=-1017 “无法解析响应” UserInfo={NSErrorFailingURLStringKey=http://api.room2shop.com/api/product/GetProducts, _kCFStreamErrorCodeKey=-1, NSErrorFailingURLKey=http://api.room2shop.com/api/product/GetProducts, NSLocalizedDescription=无法解析响应, _kCFStreamErrorDomainKey=4, NSUnderlyingError=0x78ecf180 {错误域=kCFErrorDomainCFNetwork 代码=-1017 "(null)" UserInfo={_kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-1}}}

谁能告诉我我做错了什么?我已经搜索了这个链接,但没有得到什么是错的。 URL Encode Alamofire GET params with SwiftyJSON

【问题讨论】:

    标签: ios swift alamofire swifty-json


    【解决方案1】:

    使用此代码。它正在检索以 JSON 格式正确解析的响应。

    使用 Alamofire v3.0+

    Alamofire.request(.GET, "http://api.room2shop.com/api/product/GetProducts?categoryId=22&filter=2&pageNumber=1")
            .responseJSON { response in
                debugPrint(response)
    
                switch response.result {
                case .Success(let JSON):
                    print(JSON)
                case .Failure(let error):
                    print(error)
                }
        }
    

    编辑: 接受带有 GET 类型服务的参数:

    Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
         .responseData { response in
             print(response.request)
             print(response.response)
             print(response.result)
          }
    

    在这种情况下,尽量不要操纵你的 URL 字符串,并像这样按照字典发送所有参数。

    【讨论】:

    • 是的,我知道直接 URL 给出了正确的响应。但我想传递参数@n.by.n
    • 您的 Web 服务有两种方式获取参数,或者通过字符串操作(即在 URL 字符串中提供参数)或创建接受 JSON 格式参数的服务,但在后一种情况下,您的 URL 应该是干净的里面没有任何参数。 (这是一个很好的做法)。为了在 GET 服务中将参数作为 JSON,我正在编辑我的答案。检查!
    【解决方案2】:

    我认为你应该删除“encoding: ParameterEncoding.JSON”的参数,像这样:

    Alamofire.request(.GET, strURL, parameters: params).responseJSON { (responseObject) -> Void in
    
            print(responseObject)
    
            if responseObject.result.isSuccess {
                let resJson = JSON(responseObject.result.value!)
                success(resJson)
            }
            if responseObject.result.isFailure {
                let error : NSError = responseObject.result.error!
                failure(error)
            }
    
    
    }
    

    【讨论】:

      【解决方案3】:

      您的requestGETURL 应该是这样的

          func requestGETURL(strURL: String, params: [String:String]?, success: (AnyObject?) -> Void, failure: (NSError) -> Void) {
          Alamofire.request(.GET, strURL, parameters: params).responseJSON {
              (responseObject) -> Void in
      
              print(responseObject)
      
              if responseObject.result.isSuccess {
                  let resJson = JSON(responseObject.result.value!)
                  success(resJson)
              }
              if responseObject.result.isFailure {
                  let error: NSError = responseObject.result.error!
                  failure(error)
              }
      
      
          }
      }
      

      你的问题在params 它应该是[String:String] 字典。此外,您不必声明编码encoding:ParameterEncoding.JSON

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-13
        • 2017-06-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多