Accessing DailyMile API with AFNetworking 2.0

雨燕双飞 提交于 2019-12-25 02:09:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!