【问题标题】:AFNetworking and SwiftAFNetworking 和 Swift
【发布时间】:2014-07-26 04:34:03
【问题描述】:

我正在尝试使用 Swift 获取 JSON 响应。

我嗅探了请求和响应 -> 一切正常。但是返回值始终是nil

let httpClient = AppDelegate.appDelegate().httpRequestOperationManager as AFHTTPRequestOperationManager;

let path = "/daten/wfs";
let query = "?service=WFS&request=GetFeature&version=1.1.0&typeName=ogdwien:AMPELOGD&srsName=EPSG:4326&outputFormat=json".stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding);

func successBlock(operation: AFHTTPRequestOperation!, responseObject: AnyObject!) {
    println("JSON: " + "\(responseObject)")
}

func errorBlock(operation: AFHTTPRequestOperation!, error:NSError!) {
    println("Error: " + error.localizedDescription)
}

let urlString = "\(path)" + "/" + "\(query)"
println("urlString: " + httpClient.baseURL.absoluteString + urlString)

我也试过这样:

httpClient.GET(urlString, parameters: nil,
    success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) -> Void in
        println("Success")
        println("JSON: " + "\(responseObject)")
    },
    failure:{ (operation: AFHTTPRequestOperation!, error:NSError!) -> Void in
        println("Failure")
    })

...但responseObject 似乎总是nil

编辑:

也许原因是我的AppDelegate 中可能的错误初始化:

var httpRequestOperationManager: AFHTTPRequestOperationManager? // JAVA SERVER Client

class func appDelegate() -> AppDelegate {
    return UIApplication.sharedApplication().delegate as AppDelegate
}

func configureWebservice() {
    let requestSerializer = AFJSONRequestSerializer()
    requestSerializer.setValue("1234567890", forHTTPHeaderField: "clientId")
    requestSerializer.setValue("Test", forHTTPHeaderField: "appName")
    requestSerializer.setValue("1.0.0", forHTTPHeaderField: "appVersion")

    let responseSerializer = AFJSONResponseSerializer()

    AFNetworkActivityIndicatorManager.sharedManager().enabled = true

    // ##### HTTP #####
    let baseURL = NSURL(string: "http://data.wien.gv.at");
    httpRequestOperationManager = AFHTTPRequestOperationManager(baseURL: baseURL))

    httpRequestOperationManager!.requestSerializer = requestSerializer
    httpRequestOperationManager!.responseSerializer = responseSerializer
}

任何建议我做错了什么?

【问题讨论】:

  • 我强烈建议您使用 Alamofire 而不是 AFNetworking。它是 AFNetworking 的继承者,完全用 Swift 重写。

标签: ios json swift afnetworking


【解决方案1】:
HttpManager.sharedInstance.getNewestAppList("\(self.numberofPhoto)", offset: "0", device_type: "ios",search: self.strSearch, filter: self.strFilter, onCompletion: { (responseObject: NSDictionary?, error: NSError?) -> Void in
    if error != nil {
        SwiftLoader.hide()
        self.showAlertWithMessage("\(error!.localizedFailureReason!)\n\(error!.localizedRecoverySuggestion!)")
    } else {
        SwiftLoader.hide()

        if responseObject!.valueForKey("status") as! NSString as String == "0" {
            self.showAlertWithMessage(responseObject!.valueForKey("message") as! NSString as String)
        } else {
            self.itemsArray =  responseObject!.valueForKey("data") as! NSArray
            print(self.itemsArray.count)
            self.tableCategoryDetailRef.reloadData()
        }
    }
})

import Foundation

typealias getResponse = (NSDictionary?, NSError?) -> Void

class HttpManager: NSObject {

    var AFManager: AFURLSessionManager?
    var strUrl: NSString = "url"

    class var sharedInstance:HttpManager {
        struct Singleton {
            static let instance = HttpManager()
        }

        return Singleton.instance
    }

    // MARK: - Method
    func getCount(device_type:String, onCompletion: getResponse) -> Void {
        let post: String = "device_type=\(device_type)"
        let postData: NSData = post.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)!
        let postLength:NSString = String(postData.length)
        let configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
        AFManager = AFURLSessionManager(sessionConfiguration: configuration)
        let URL: NSURL = NSURL(string: "\(strUrl)/count" as String)!
        let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: URL)
        urlRequest.HTTPMethod = "POST"
        urlRequest.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
        urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        urlRequest.HTTPBody = postData

        let task =  AFManager?.dataTaskWithRequest(urlRequest) { (data, response, error) in
            if response == nil {
                SwiftLoader.hide()
            } else {
                let responseDict:NSDictionary = response as! NSDictionary
                onCompletion(responseDict,error)
            }
        }

        task!.resume()
    }
}

【讨论】:

    【解决方案2】:

    您可以使用 Swift 与 Objective-C 框架的互操作性,但现在有一个官方库,让我们来看看:

    https://github.com/Alamofire/Alamofire

    这个库是用原生 Swift 编写的,来自 AFNetworking 的创建者。当你迁移到 Swift 时,你可能会想要寻找这种东西。我试过了,它很棒,就像它的前身一样。

    【讨论】:

      【解决方案3】:

      Swift 与 Objective-C 代码完全兼容,因此您的问题与 Swift 本身有关。在AFNetworking 中,responseObject 可以 有时是nil。这包括以下情况:

      • 返回了204 No Content 状态码,
      • 如果输出流设置为写入文件,
      • 如果验证期间的错误不是NSURLErrorCannotDecodeContentData(例如不可接受的内容类型)

      查看#740#1280 了解更多信息。

      【讨论】:

      • 感谢您的提示……看来我的基本初始化是错误的。我还没有弄清楚为什么。我将信息添加到我的原始帖子中
      • 这是一个与服务器相关的问题 -> 我尝试了另一个 URL 并且它有效。谢谢!
      猜你喜欢
      • 2014-07-30
      • 1970-01-01
      • 2017-10-27
      • 2016-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多