简体   繁体   English

快速的AFNetworking 2.0中的Web服务调用问题

[英]Web Service call issue in AFNetworking 2.0 in swift

I am using AFNetworking 2.0 in swift for calling The api is as follows http://api.openweathermap.org/data/2.5/weather?q=Delhi 我正在迅速使用AFNetworking 2.0进行调用api如下所示:http: //api.openweathermap.org/data/2.5/weather?q=Delhi

When we hit this URL on browser, we will get a JSON. 当我们在浏览器中点击此URL时,我们将获得一个JSON。 This is a GET request. 这是一个GET请求。 On hitting this api on postman also produces the same result Now I made a helper class WebService.swift and in which I am calling a success and a error block 在邮递员上击中此api时,也会产生相同的结果。现在,我创建了一个辅助类WebService.swift,在其中调用成功和错误块

My WebService.swift class is as follows 我的WebService.swift类如下

import UIKit

class WebService: NSObject {

static let sharedInstance = WebService()


func weatherService(loginCode:String, requestData:NSMutableDictionary, successBlock: (response: AnyObject!,headers: NSDictionary, callBack:String ) -> Void, errorBlock: (error: NSError,headers:NSDictionary,responseObject:AnyObject!) -> Void){

    var serviceURL = "http://api.openweathermap.org/data/2.5/weather?q=Delhi"
    var manager = AFHTTPRequestOperationManager()
    manager.requestSerializer = AFJSONRequestSerializer()

    manager.responseSerializer.acceptableContentTypes = NSSet(objects: "text/html","application/json")  as? Set<NSObject>


    manager.requestSerializer.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

    manager.GET(serviceURL, parameters: requestData, success: { (operation:AFHTTPRequestOperation, responseObject:AnyObject) -> Void in
        var headersCollection = operation.valueForKey("response")?.valueForKey("allHeaderFields") as! NSDictionary
        var headers = headersCollection.mutableCopy() as! NSMutableDictionary
        headers["statusCode"] = NSNumber(integer: operation.response!.statusCode)
           var _callBack = requestData["callBack"] as! String
        successBlock(response:responseObject,headers:headers,callBack: _callBack)


        }) { (operation:AFHTTPRequestOperation, error:NSError) -> Void in


            var headersCollection = operation.valueForKey("response")?.valueForKey("allHeaderFields") as! NSDictionary
            var headers = headersCollection.mutableCopy() as! NSMutableDictionary
            headers["statusCode"] = NSNumber(integer: operation.response!.statusCode)

            errorBlock(error: error, headers: headers, responseObject: operation.responseObject)
    }


}

} 

The method I am calling from my view controller in view did load 我从视图控制器中调用的方法确实加载了

        let params = ["callBack": String(format: "%d", "weatherAPI")] as NSMutableDictionary

        WebService.sharedInstance.weatherService("URLHardcodedInWebServiceClass", requestData: params, successBlock: { (response, headers, callBack) -> Void in

            var dict = response as! NSDictionary


                println("Success with \(callBack)")

            }) { (error, headers, responseObject) -> Void in

                println("failed")

        }

Now the problem is that everytime I am going in the error block of webservice class where the contents of headers which is a NSMutableDictionary is 现在的问题是,每次我进入webservice类的错误块时,其中的头内容为NSMutableDictionary

{
"Access-Control-Allow-Credentials" = true;
"Access-Control-Allow-Methods" = "GET, POST";
"Access-Control-Allow-Origin" = "*";
Connection = "keep-alive";
"Content-Type" = "application/json; charset=utf-8";
Date = "Mon, 31 Aug 2015 18:53:36 GMT";
Server = nginx;
"Transfer-Encoding" = Identity;
"X-Source" = back;
statusCode = 200;
}  

And when I see the NSError it shows 当我看到NSError时

Printing description of error: 打印错误说明:

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" 
(JSON text did not start with array or object and option to allow fragments not set.) 
UserInfo=0x7fdb6865d5a0 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

Status code I receive is 200 And when I do this po operation.responseString I get 我收到的状态码是200并且当我执行此po operation.responseString我得到 在此处输入图片说明

The json is there but with errors and I guess it is not formed correctly. json在那里,但有错误,我想它的格式不正确。 I tried my other service with content-type as text/html and it worked fine as I have to change the line 我尝试使用内容类型为text / html的其他服务,但由于必须更改该行,因此效果很好

manager.requestSerializer.setValue("text/html; charset=utf-8", forHTTPHeaderField: "Content-Type")

And URL for other service is http://bluesapphireindia.in/WebService.asmx/GetEmployessJSON 其他服务的URL是http://bluesapphireindia.in/WebService.asmx/GetEmployessJSON

It is working fine in this piece of code 在这段代码中工作正常

What can be the reason. 可能是什么原因。 Can anyone help me out in this. 谁能帮我这个忙。 Thanks 谢谢

I have done same thing in my current project in different way by using AFHTTPRequestOperation class from AFNetworking in Swift . 我以做在不同的方式我当前的项目同样的事情AFHTTPRequestOperation从类AFNetworkingSwift I hope it may help you. 希望对您有帮助。

 func afnStartConnectionWithURL(urlEndPoint: String, enumName: enumAPIname, httpMethod: String, httpBody: AnyObject, headerValue: String){

    var _URL = NSURL(string: kBaseURL + urlEndPoint)
    var currentTime: NSTimeInterval = 10

    var request = NSMutableURLRequest(URL: _URL!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: currentTime)
    request.HTTPMethod = httpMethod
    var err: NSError?
    if(httpMethod == kPOST){

        let jsonData:NSData = NSJSONSerialization.dataWithJSONObject(httpBody, options: .PrettyPrinted, error: nil)!
        request.HTTPBody = jsonData
    }
    request.addValue(headerValue, forHTTPHeaderField: "Authorization")
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    var op = AFHTTPRequestOperation(request: request)
    op.responseSerializer = AFJSONResponseSerializer()
    op.setCompletionBlockWithSuccess({ (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) -> Void in

        operation.cancel()
        var dicConnectionResponse:NSDictionary = responseObject as! NSDictionary
        self.afnConnection_Result(dicConnectionResponse, enumName: enumName, afhttpRequestOperation: operation)

        },

        failure: { (operation: AFHTTPRequestOperation!, error:NSError!) -> Void in

            operation.cancel()
            self.afnConnection_Error(operation, enumName: enumName, error: error)
    })

    op.start()
}

here the afnConnection_Result and afnConnection_Error are call back delegate methods. 这里的afnConnection_ResultafnConnection_Error是回调委托方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM