AFNetworking和Swift

14

我想使用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
}

有什么建议吗?我做错了什么吗?


1
我强烈建议您使用Alamofire而不是AFNetworking。它是AFNetworking的继承者,完全重写并为Swift设计。 - Jeehut
3个回答

8
Swift完全兼容Objective-C代码,所以你的问题与Swift本身无关。在“AFNetworking”中,“responseObject”有时可能为“nil”。这包括以下情况:
  • 返回了“204 No Content”状态码,
  • 如果输出流设置为写入文件,
  • 如果验证过程中出现的错误不是“NSURLErrorCannotDecodeContentData”(例如,不可接受的内容类型)
请查看#740#1280以获取更多信息。

谢谢提示...看起来我的基本初始化有问题。我还没有弄清楚为什么。我会将这些信息添加到我的原始帖子中。 - user707342
1
这是一个与服务器相关的问题 -> 我尝试了另一个URL,它可以工作。谢谢! - user707342

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

https://github.com/Alamofire/Alamofire

这个库是用纯Swift编写的,由AFNetworking的创作者编写。当你转向Swift时,你可能会想寻找这种类型的库。我尝试了一下,它很棒,就像它的前身一样。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接