问题
So I'm making a JSON request from an https site (after retrieving the auth token) and like a dozen other problems with AFNetworking on stack overflow, I'm getting this 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=0x8dc2860 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
The code I'm using to make this request is like such:
AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
[requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
//Set auth header...
NSString *accessToken = [[[self.dailymileAuthentication oauthClient] accessToken] accessToken];
[requestSerializer setAuthorizationHeaderFieldWithToken:accessToken];
AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
[requestManager setRequestSerializer:requestSerializer];
[requestManager setResponseSerializer:[AFJSONResponseSerializer serializer]];
[requestManager GET:[profileURL description]
parameters:nil
success:^(AFHTTPRequestOperation *operation, id response) {
NSLog(@"JSON: %@", response);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
The URL is: https://api.dailymile.com/people/me.json
I'm working out of a public GitHub repo if anyone is interested in checking out the full codebase (note: you don't need to to understand the problem, this is just optional): https://github.com/thepost/Dailymile-iOS
What do I need to do to make an authenticated JSON request?
I have no idea if I'm using AFNetworking correctly or not. To be honest, there isn't a lot of documentation out there for AFNetworking 2 yet.
回答1:
I'm not sure what the confusion is about; the error is quite clear:
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=0x8dc2860 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
The JSON response from DailyMile is not valid, as it doesn't have an array or object as its root value.
If the value is indeed JSON, and should be parsed as JSON, you can set the readingOptions of the responseSerializer to allow fragments.
What I suspect, however, is that your API endpoint is not actually returning JSON, but a plain text response with the wrong Content-Type
header.
来源:https://stackoverflow.com/questions/20480072/accessing-dailymile-api-with-afnetworking-2-0