我在swift中使用AFNetworking 2.0进行呼叫 api如下 http://api.openweathermap.org/data/2.5/weather?q=Delhi
当我们在浏览器上点击此URL时,我们将获得一个JSON。这是一个GET请求。在邮递员上打这个api也会产生相同的结果 现在我创建了一个帮助类WebService.swift,我在其中调用了一个成功和一个错误块
我的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)
}
}
}
我在视图中从视图控制器调用的方法已加载
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")
}
现在的问题是每次我进入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;
}
当我看到它显示的NSError时
打印错误说明:
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.}
我收到的状态代码是200 而当我这样做 po operation.responseString 我明白了
json在那里,但有错误,我猜它没有正确形成。我尝试使用内容类型作为text / html的其他服务,它工作正常,因为我必须更改行
manager.requestSerializer.setValue("text/html; charset=utf-8", forHTTPHeaderField: "Content-Type")
其他服务的URL是 http://bluesapphireindia.in/WebService.asmx/GetEmployessJSON
这段代码工作正常
可能是什么原因。任何人都可以帮助我。感谢
答案 0 :(得分:0)
我使用AFHTTPRequestOperation
AFNetworking
中的Swift
类以不同的方式在我当前的项目中做了同样的事情。我希望它可以帮助你。
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()
}
此处afnConnection_Result
和afnConnection_Error
是回调委托方法。