I'm trying to understand how to use and have back the right value from the dropbox longpool_delta api call. I successfully retrieve the cursor value but always get the 400 code as response. Can anyone help me to fix it or help me to understand where i'm wrong?
For quickly test i've setup the request with AFNetworking.
Below the sample code.
Thanks
NSString *myUrl = #"https://api.dropbox.com/1/delta/";
NSURL *url = [NSURL URLWithString:myUrl];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//here set the header with access token with oAuth2 api
[request setValue: [self headerForApiCall] forHTTPHeaderField:#"Authorization"];
request.timeoutInterval = 90.0;
[request setHTTPMethod:#"POST"];
__weak typeof(self) weakSelf = self;
AFJSONRequestOperation * operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSString* cursor = JSON[#"cursor"];
NSString *myUrl = [NSString stringWithFormat:#"https://api-notify.dropbox.com/1/longpoll_delta/?cursor=%#",cursor];
NSURL *url = [NSURL URLWithString:myUrl];
NSMutableURLRequest *request2 = [NSMutableURLRequest requestWithURL:url];
request2.timeoutInterval = 90.0;
[request2 setHTTPMethod:#"GET"];
AFJSONRequestOperation * operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request2 success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"long %#",JSON);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"failure long %#",response.description);
}];
[operation start];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"failure %#",response.description);
}];
[operation start];
[edit]
As suggested here the response code 400 from the failure block
status code: 400, headers {
"Cache-Control" = "no-cache";
Connection = "keep-alive";
"Content-Type" = "text/plain";
Date = "Wed, 14 May 2014 16:04:28 GMT";
Pragma = "no-cache";
Server = nginx;
"Transfer-Encoding" = Identity;
"X-DB-Timeout" = 120;
}
removing / the response always from the failure block but with a (null) value
Error 400 is from bad parameters, I think your problem is here :
NSString *myUrl = [NSString stringWithFormat:#"https://api-notify.dropbox.com/1/longpoll_delta/?cursor=%#",cursor];
Try to remove the / between longpoll_delta and ? as follow :
NSString *myUrl = [NSString stringWithFormat:#"https://api-notify.dropbox.com/1/longpoll_delta?cursor=%#",cursor];
By the way should create a Dropbox HTTP client which will help you a lot to manage your request. Create a class which inherits from AFHTTPClient. your create a singleton as follow :
+ (DBAPIClient *)sharedClientWithBaseUrl:(NSString *)baseUrl {
static DBAPIClient *sharedInstance = nil;
static dispatch_once_t apiToken;
dispatch_once(&apiToken, ^{
sharedInstance = [[DBAPIClient alloc] initWithBaseURL:[NSURL URLWithString:#"https://api.dropbox.com/1/"]];
// Do any other initialisation stuff here
});
return sharedInstance;
}
- (id)initWithBaseURL:(NSURL *)url {
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
return self;
}
In this way you'll be able to use like this which is much more simple :
NSDictionary *params = // Your params;
[[DBPIClient sharedClient]
getPath://the endpoint you want access to
parameters:params
success:^(AFHTTPRequestOperation *operation, id JSON) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
Related
I'm tring to use the etag to cache my images, the first time it downloads all the images like it should however the second time it does too when it should enter the failed block with 304.
I've tried making the request externally and I get 304 like I should, it's just with AFNetworking that i'm having trouble
NSString *urlString = [API_BASE_URL_PHOTOS stringByAppendingPathComponent:[photo getPathToPhoto]];
NSString *properlyEscapedURL = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:properlyEscapedURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
if ([UserDefaultManager getEtagForKey:photo.nom] != nil) {
[request setValue:[UserDefaultManager getEtagForKey:photo.nom] forHTTPHeaderField:ETAG_IF_NONE_MATCH];
}
[request setHTTPMethod:API_METHOD_GET];
AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request imageProcessingBlock:nil
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
[FileUtils createDirectoryInDocumentsWithFileName:photo.folderName];
NSString *docPath = [FileUtils getPathInDocumentsWithFileName:[photo getPathToPhoto]];
// Save Image
NSData *imageData = UIImageJPEGRepresentation(image, 90);
[imageData writeToFile:docPath atomically:YES];
if ([response respondsToSelector:#selector(allHeaderFields)]) {
NSDictionary *allHeaderFields = [response allHeaderFields];
[UserDefaultManager setEtag:[allHeaderFields objectForKey:ETAG] forKey:photo.nom];
}
if ([[DownloadManager sharedManager].downloadQueue.operations count] == 0) {
[[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_DOWNLOAD_ALL_PHOTOS_FINISHED object:nil];
}
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
if (response.statusCode != RESPONSE_CODE_PHOTO_UP_TO_DATE) {
LogDebug(#"%#", [error localizedDescription]);
}
}];
I managed to fix this by changing my request to
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:60];
hope that this helps
I am using AFNetworking to obtain JSON from a URL, the JSON is parsed and is supposed to be converted into an NSData format which is then in turn put into an array. However it doesn't seem to be working. I think i'm being stupid because it worked previously but now-
-(void)loadFromServer{
NSString *trendsURL = [NSString stringWithFormat:#"http://myurl.com/data.json"];
NSURL *url = [NSURL URLWithString:trendsURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation
JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id json) {
self.results = [json valueForKeyPath:#"data"];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
}];
[operation start];
NSError *anError = nil;
NSArray *parsedElements = [NSJSONSerialization JSONObjectWithData:elementsData
options:NSJSONReadingAllowFragments
error:&anError];
for (NSDictionary *aModuleDict in parsedElements){
MosData *aMosModule = [[MosData alloc] initWithDictionary:aModuleDict];
[elements addObject:aMosModule];
}
}
The data is displayed in a collection like view separately, there is no problem with this separate view as it works when I access data from a file rather than server.
-(void)loadFromDisk{
NSString *pathString = [[NSBundle mainBundle] pathForResource:#"data" ofType:#"json"];
NSData *elementsData = [NSData dataWithContentsOfFile:pathString];
NSError *anError = nil;
NSArray *parsedElements = [NSJSONSerialization JSONObjectWithData:elementsData
options:NSJSONReadingAllowFragments
error:&anError];
for (NSDictionary *aModuleDict in parsedElements){
MosData *aMosModule = [[MosData alloc] initWithDictionary:aModuleDict];
[elements addObject:aMosModule];
}
}
The JSON that is fetched is like so:
{
"imageLink": "http://link.com/image.jpg",
"size": 1,
"title": "Food"
}
I gave it another go, and still it's not working. results is a declared NSArray.
-(void)loadFromServer{
NSString *trendsURL = [NSString stringWithFormat:#"http://url.com/data.json"];
NSURL *url = [NSURL URLWithString:trendsURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation
JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id json) {
NSLog(#"Custom Mosaic: %#", json);
self.results = [json valueForKeyPath:#"data"];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
}];
[operation start];
for (NSDictionary *aModuleDict in self.results){
MosData *aMosModule = [[MosData alloc] initWithDictionary:aModuleDict];
[elements addObject:aMosModule];
}
}
I think the issue might actually be this having played around a little, for some reason, it won't pick up the results of the data parsed in the AFNetworking operation.
-(id)init{
self = [super init];
if (self){
elements = [[NSMutableArray alloc] init];
[self loadFromServer];
}
return self;
}
// WWDC 2012 proposed method
+ (CustomMosDatasource *)sharedInstance {
static CustomMosDatasource *sharedInstance;
if (sharedInstance == nil)
sharedInstance = [CustomMosDatasource new];
return sharedInstance;
}
#pragma mark - MosViewDatasourceProtocol
-(NSArray *)mosElements{
NSArray *retVal = elements;
return retVal;
}
The results of the log is just JSON:
Custom Mosaic: {
data = (
{
imageFilename = "http://distilleryimage6.instagram.com/9969123a6af311e2b6c722000a9d0edd_7.jpg";
size = 1;
title = "Title";
},
AFJSONRequestOperation *operation = [AFJSONRequestOperation
JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id json) {
self.results = [json valueForKeyPath:#"data"];
NSError *anError = nil;
NSArray *parsedElements = [NSJSONSerialization JSONObjectWithData:elementsData
options:NSJSONReadingAllowFragments
error:&anError];
for (NSDictionary *aModuleDict in parsedElements){
MosData *aMosModule = [[MosData alloc] initWithDictionary:aModuleDict];
[elements addObject:aMosModule];
}
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
}];
[operation start];
Your json don't seem to have keyPath "data", remove the valueForKeyPath:#"data", please paste the result of "NSLog(#"Custom Mosaic: %#", json)" in your question.
The operation is asynchronized. The success block is called after the request returns data. Please put code in the success block like this
-(void)loadFromServer{
NSString *trendsURL = [NSString stringWithFormat:#"http://url.com/data.json"];
NSURL *url = [NSURL URLWithString:trendsURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation
JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id json) {
NSLog(#"Custom Mosaic: %#", json);
// your json doesn't have keyPath "data"
self.results = json;
// Codes moved into success block
for (NSDictionary *aModuleDict in self.results){
MosData *aMosModule = [[MosData alloc] initWithDictionary:aModuleDict];
[elements addObject:aMosModule];
}
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
}];
[operation start];
}
I am trying to make a POST request using AFNetworking. I went through SO and found that I need to include httpClient.parameterEncoding = AFJSONParameterEncoding
It still doesn't work even after making that change. Anything else I am missing ? Here is the code
NSDictionary *subDictionaryUsers = [[NSDictionary alloc]initWithObjectsAndKeys:myObject.name,#"name", myObject.topic_description,#"description", nil];
NSString *_restPath = [NSString stringWithFormat:#"spaces.json/auth_token=%#",myObject.auth_token];
NSDictionary *params = [[NSDictionary alloc]initWithObjectsAndKeys:subDictionaryUsers,#"space",nil];
myAppAFNClient *httpClient = [myAppAFNClient sharedClient];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:_restPath parameters:params];
httpClient.parameterEncoding = AFJSONParameterEncoding;
[httpClient getJsonResponse:request notificationString:#"add.hydramixer.topics"];
myAppAFNClient.m
-(void)getJsonResponse:(NSURLRequest *)_request notificationString:(NSString *)notifString{
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:_request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
if([notifString length] != 0){
// handling success
}
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON){
// handling errors
}];
[operation start];
}
I'm doing a request to the server and the server returns a JSON. AFNetworking framework returns a wrong formatted JSON.
This is what the server sends:
{"email":"XXXXXXX","firstName":"XXXXXX","lastName":"XXXXXXX","gender":"male","userToken":"XXXXXXXXXXX"}
This is what AFNetworking receives:
{
email = "XXXXXXX";
firstName = XXXXXX;
gender = male;
lastName = XXXXXXX;
token = XXXXXXXXXXXX;
}
My code:
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:server_ip]];
NSURLRequest *request = [client requestWithMethod:#"POST" path:path parameters:params];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"%#", JSON);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
}];
[operation start];
The object you are printing out is the NSDictionary representation of the JSON received from the server.
If you want to see the raw JSON returned from the server, you should look at the responseString of the operation:
NSLog(#"%#", operation.responseString);
I want to "POST" a JSON value to server and response a json databack.
The URL: http://solok.com:8080/soloo/phone/execute?content={"method":"tet_123","version","1"}, can get the right value(JSON) in browser.
ASIHTTPRequest way:
NSDictionary *postDic = [NSDictionary dictionaryWithObjectsAndKeys:#"tet_123",#"method",#"1",#"version",nil];
NSString *postString;
//Then convert the "postDic" to NSString, the value is:{"method":"tet_123","version","1"} assign to postString;
psotString = ...;
ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
[req setRequestMethod:#"POST"];
[req setPostValue:posStr forKey:#"content"];
[req startAsynchronous];
[req setDelegate:self];
[req setCompletionBlock:^{
NSData *d = [req responseData];
NSLog(#"respond is %#".d);
}
It works smoothly! But AFNetworkding is not, here is the code;
NSURL *url = [NSURL URLWithString:#"http://localhost:8080"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:#"tet_123",#"method",#"1",#"version",nil];
NSDictionary *dic1 = [NSDictionary dictionaryWithObjectsAndKeys:dic,#"content", nil];
[httpClient postPath:#"/soloo/phone/execute" parameters:dic1 success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *d = (NSDictionary *)responseObject;
NSLog(#"success is %#",d);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"fail");
}];
The output is: success is <>.
or i use another way of AFNetworking:
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"path:#"/soloo/phone/execute" parameters:dic1];
AFJSONRequestOperation *ope = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"response %d",response.statusCode);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"fail%d JSON %#",response.statusCode,JSON);
}];
The respond code is 200, which means connection is correct, but still no the correct result.
Not sure why. Any help, thank in advance!
The reason is is the backend is a "GET" method, but i did "POST", meanwhile, i forgot: [Operation start] method.