NSData到[String:AnyObject]

时间:2016-06-04 17:10:25

标签: ios swift alamofire

我有一些遗留代码,我正在移植到Swift 2.0,这会产生错误,之前它已经运行正常。

错误是:Cast from 'NSData?' to unrelated type '[String : AnyObject]' always fails

在将代码移动到新项目之前,我没有收到错误,代码运行正常。

代码:

    func RestApiRequest(RestPath RestPath:String, Method:Alamofire.Method, Headers:NSDictionary?, Body:AnyObject?,ContentType:String,
    OnCompletion:(StatusCode:Int, ResponseData:NSData, inout ResponseError:NSError?) -> (Void))
{
    //Set REST url to be called
    let mutableURLRequest = NSMutableURLRequest(URL:  NSURL(string: "\(self.baseUrl!)\(RestPath)")!)
    //Store body data if it exists
    var data:  NSData?
    //Check if body value is set
    if(Body != nil) {

        //Check if body is a dictionary
        if(Body is NSDictionary){
            //Convert to JSON
            let jsonBody = JSON(Body!)
            data = try! jsonBody.rawData()
        }
        //Check if body is an array
        else if(Body is NSArray) {
            //convert to json
            let jsonBody = JSON(Body!)
            data = try! jsonBody.rawData()
        }
        else {
            let bodyData = Body?.dataUsingEncoding(NSUTF8StringEncoding)
            data = bodyData
        }
    }

    let manager = Alamofire.Manager.sharedInstance
    manager.session.configuration.HTTPAdditionalHeaders = Headers as? [NSObject : AnyObject]

    manager.request(Method,mutableURLRequest, parameters: data as? [String : AnyObject], encoding: .Custom({ (convertible, params) in

        let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest
        if(data != nil) {
            mutableRequest.HTTPBody = data
        }

        return (mutableRequest, nil)
    })).response { (request, response, data, error) in
        var _error = error
        print(request)
        print(NSString(data: data!, encoding:NSUTF8StringEncoding))
        OnCompletion(StatusCode: (response?.statusCode)!, ResponseData: data!, ResponseError: &_error)

    } 
}

}

有没有办法成功进行此转换而不会产生错误?

0 个答案:

没有答案