I just wanted to ask you if anyone can help me parsing the returned data from the Twitpic API?
I'm creating a HTTPFormRequest using the ASIHTTPRequest Wrapper for Cocoa. This all happens in an iPhone application:
NSURL *url = [NSURL URLWithString:#"http://twitpic.com/api/upload"];
NSString *username = t_user;
NSString *password = t_pass;
NSData *twitpicImage = UIImagePNGRepresentation(imageView.image);
// Now, set up the post data:
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[request setPostValue:twitpicImage forKey:#"media"];
[request setPostValue:username forKey:#"username"];
[request setPostValue:password forKey:#"password"];
[request setData:twitpicImage forKey:#"media"];
// Initiate the WebService request
[request start];
if ([request error]) {
NSLog(#"%#", [request error]);
} else if ([request responseString]) {
NSLog(#"%#", [request responseString]);
}}
Now comes the hard part, I don't know how to parse the data that is in [request responseString]. I know I need to use NSXMLParser, but I dunno how to use it. All I need is to get the url of the image.
Thx in advance.
Feel free to have a look at my little XML parse classes here http://www.memention.com/blog/2009/10/31/The-XML-Runner.html
I have started to use them for parsing the response from image upload to yfrog.com
Basically I do like this...
In NameValueParser.m I changed the entry tag to rsp like this
entryName = [[NSString stringWithString:#"rsp"] retain];
then where the response has been received I parse it like this
NameValueParser *parser = [NameValueParser parser];
[parser addFieldName:#"statusid"];
[parser addFieldName:#"userid"];
[parser addFieldName:#"mediaid"];
[parser addFieldName:#"mediaurl"];
[parser addFieldName:#"err"];
[parser parseData:responseData]; // the response received by ASIHTTPRequest
NSArray *rspArray = [parser list];
NSLog(#"%#", rspArray); // Have a look at it here
Try it as written at the bottom of this tutorial click here using NSScanner. They are showing exactly what you need, retrieving only the mediaurl = URL of uploaded image.
NSScanner *scanner = [NSScanner scannerWithString:responseString]; ...
GSTwitPicEngine does XML and JSON parsing both: http://github.com/Gurpartap/GSTwitPicEngine
Though, why not use JSON format for the Twitpic API responses? It's easy to parse and deal with using yajl, TouchJSON, json-framework or other Cocoa JSON libraries
Related
I am trying to post an image to reddit; however, I only kind of know what I am doing. I am using objective c for my iphone app.
Prior to the code listed below I obtain a modhash and cookie by logging in prior to the upload and use NSLog to determine that I truly am receiving them. Then I use a JSON Parser to separate them into separate variables.
I was not sure what all of the POST argument values were supposed to be so I kind of guessed. The necessary arguments are uh, file, formid, header, ing_type, name, and sponsor.
The documentation for reddit api is http://www.reddit.com/dev/api I believe that I want to use the POST /api/upload_sr_img method...
NSURL *url = [NSURL URLWithString:#"http://www.reddit.com/api/upload_sr_img"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
NSString *httpBody = [NSString stringWithFormat:#"?uh=%#&file=%#&formid=''header=%#&img_type=%#&name=%#&sponsor=%#",modhash,UIImagePNGRepresentation(self.memeImage.image),#"test",#"png",#"Drew",#"Drew'sApp"];
[request setHTTPBody:[httpBody dataUsingEncoding:NSASCIIStringEncoding]];
NSURLResponse *response = NULL;
NSError *imgError = NULL;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&imgError];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingMutableContainers error:nil];
NSDictionary *responseJson = [json valueForKey:#"json"];
NSLog(#"response is: %#",response);
NSLog(#"imgError is: %#",imgError);
NSLog(#"result is: %#",result);
NSLog(#"json is: %#",json);
NSLog(#"responseJson is: %#",responseJson);
Could use any help I can get.
Also, I was not sure if I needed to send a content-type or even what it would be.
Thanks for your help.
Check this library: https://github.com/MattFoley/MFRedditPostController
You can use the provided UI or create your own.
I am using ASIFormDataRequest to call a web service with video file. it workes fine if video is small but if video is about 30 seconds or above then its response return as __NSCFString or sometime __NSCFConstantString
my code is as below.
__block ASIFormDataRequest *request=[[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:APP_APIURL]];
[request setPostValue:strVal forKey:#"jsonRequest"];
if (videoData) {
[request setData:videoData withFileName:videoName andContentType:nil forKey:#"videoFile"];
}
[request startSynchronous];
request.timeOutSeconds=999999999;
// response
NSString *strResponse=[request responseString];
if (strResponse) {
SBJsonParser *parser=[[SBJsonParser alloc] init];
NSMutableDictionary *dicData=[[parser objectWithString:strResponse] valueForKey:#"uploadVideo"];
Please help me to solve this issue.
Shivam
Here are few solutions to your problem:
Use introspection and check the returned object for it's class. If you're getting a "constant" string, probably it's not what you're expecting. Print it or check it's contents.
If you're receiving a video file - use [request responseData] or better, use the file saving techniques described in ASIHTTPRequest library. How can you download a file and parse json response at the same time?
Use JSONKit - IMHO the fastest json parser.
I am trying to use the ASIDownloadCache from the ASIHTTPRequest library. I think I have it almost set up but the data I am printing to the log is a bunch of numbers.. I think it might be a formatting problem.. but I would like to run it past someone with more experience first to make sure I'm doing it correctly and then to hopefully help me fix the issue.
The code belows shows you how I am setting up my cache, I am using this view for several data sets, hence the need to use an if statement so that I am only setting up the cache on specific data.
- (IBAction)setRequestString:(NSString *)string
{
//Set database address
NSMutableString *databaseURL = [[NSMutableString alloc] initWithString:#"http://***.***.***.***:8888/codeData/"]; // iphone development
//PHP file name is being set from the parent view
[databaseURL appendString:string];
//call ASIHTTP delegates (Used to connect to database)
NSURL *url = [NSURL URLWithString:databaseURL];
checkDataSet = [[NSString alloc] initWithFormat:string]; //Loads ICMfg.xml into checkDataSet for setting up cache
//Create If statments here
if ([checkDataSet isEqualToString:#"ICMfg.xml"]) {
//Cache stuff goes in here
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadCache:[ASIDownloadCache sharedCache]];
[request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
[request setCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy];
[request setSecondsToCache:60*60*24*30]; // Cache for 30 days
[request setDelegate:self]; // A delegate must be specified
[request startSynchronous];
//[request setDidFinishSelector:#selector(requestFinished:)]; // And an appropriate
}
else
{
//this else statments lets all of the other datasets come through here
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setDelegate:self];
[request startAsynchronous];
}
}
From here, when [checkDataSet isEqualToString:#"ICMfg.xml"] is true it will set the cache parameters and then calls the following method where I get everything ready to parse my information
- (void)requestFinished:(ASIHTTPRequest *)request
{
if ([checkDataSet isEqualToString:#"ICMfg.xml"]) {
BOOL success = [request didUseCachedResponse];
NSLog(#"------------>>>>>>> Success is %#\n", (success ? #"YES" : #"NO"));
responseString = [request responseString];
capturedResponseData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"%#", capturedResponseData); //this prints out the weird data.
[self startTheParsingProcess:capturedResponseData];
}
else
{
responseString = [request responseString]; //Pass requested text from server over to NSString
capturedResponseData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
[self startTheParsingProcess:capturedResponseData];
}
}
From here, I check my nslog to see the result of that NSlog and it spits out a bunch of numbers, below is a small section of the output. The next step for me is to check to see if anything is actually being parsed.. and also to see if the cache is working or not.. then I need to figure out hopefully with your help how to format the data correctly if thats my main problem..
also I would like to ask how to get this working asynchronously as currently I can only get it to work synchonosly.
2011-11-09 09:29:55.216 code[3968:207] ------------>>>>>>> Success is YES
2011-11-09 09:29:55.239 code[3968:207] <3c3f786d 6c207665 7273696f 6e3d2231 2e302220 656e636f 64696e67 3d225554 462d3822 3f3e0d0a 3c494345 6e673e3c 52657375 6c742044 42566572 73696f6e 3d223132 33223e3c 5461626c 65733e3c 5461626c 65205461 626c654e 616d653d 2249434d 6667223e 3c526f77 733e3c52 6f77204d 414e5546 41435455 52455249 443d2237 30362220 4d414e55 46414354 55524552 3d22412d 445a4722 2049534c 4f434b4d 414e5546 41435455 5245523d 22462220 49535645 4849434c 453d2246 223e3c2f 526f773e 3c526f77 204d414e 55464143 54555245 5249443d 22333138 22204d41 4e554641 43545552 45523d22 412e522e 452e2220 49534c4f 434b4d41 4e554641 43545552 45523d22 46222049
any help would be greatly appreciated.
I don't see anything that immediately sticks out in your code as wrong.
The NSLog() is printing an NSData object, which is binary data so the hexadecimal numbers you are seeing are the representations of the bytes which is exactly what you would expect.
The NSData Class Reference:
description
Returns an NSString object that contains a hexadecimal
representation of the receiver’s contents.
(NSString *)description
Return Value
An NSString object that contains a hexadecimal representation of the receiver’s contents in
NSData property list format.
If you want to print out the string representation of this data, use:
NSString *capturedResponseString = [NSString stringWithUTF8String:[capturedResponseData bytes]];
I'm rather new to trying to figure out how JSON and the DropBox API function with the iphone SDK that DB has release for the iPhone. I understand how both technologies work in general and that you have to build a dictionary into a request and get another dictionary back, but I can't find a solid example of how to do anything specifically enough online in Objective C.
I just need one example of how to retrieve for instance the user's profile information by creating a JSON request to fetch info from the drop-box server.
I've been able to log the user in and linking the device using the consumer key and consumer secret but what's next I'm a little at a loss.
MANY thanks for any guidance or examples.
To send your data
Example for POST methods:
url = #"https://api.dropbox.com/<version>/account/"
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:value forKey:#"callback"];
Example for GET methods (URL queries):
NSString *urlString = [[[NSString alloc] initWithString:#"https://api.dropbox.com/<version>/account/info
"] autorelease];
urlString = [urlString stringByAppendingFormat:#"?callback=whatever&status_in_response=something"];
NSURL *url = [[NSURL alloc] initWithString:urlString];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request setDidFinishSelector:#selector(requestDidFinishForThreadID:)];
[request startAsynchronous];
To retrieve JSON values and convert them into Dictionary
SBJsonParser *json = [[SBJsonParser alloc] init];
NSDictionary *dict = (NSDictionary*)[json objectWithString:responseString];
You will need JSON Framework: http://code.google.com/p/json-framework/
And also ASIHTTPRequest: http://allseeing-i.com/ASIHTTPRequest/
Haven't tested it with dropbox, but should be this way.
I'm using Three20 and want to use JSON to populate my TTPhotoViewController.
If I go to a web address, let's say,
www.bbc.com/jsonoutput
I get the following
{"name":"MyName","curNiceDate":"Wed 29 Dec 10","images":["UK\/2010\/12\/29\/1.jpg","US\/2010\/12\/29\/2.jpg","EU``\/2010\/12\/29\/3.jpg","FR\/2010\/12\/29\/4.jpg","FR\/2010\/12\/29\/5.jpg","FR\/2010\/12\/29\/6.jpg","FR\/2010\/12\/29\/7.jpg","FR\/2010\/12\/29\/8.jpg","FR\/2010\/12\/29\/9.jpg"]}
I want to pick out images which are in www.bbc.com/images/.
All those directories are locations of images relevant from the above address. How would I go about pulling out this information from the JSON output and make it into a URL which will look like this
www.bbc.com/UK/2010/12/29/1.jpg
www.bbc.com/US/2010/12/29/2.jpg
www.bbc.com/EU/2010/12/29/3.jpg
www.bbc.com/FR/2010/12/29/4.jpg
So I can feed it into the TTPhotoView Picker.
Any help please?
I've been happy with TouchJSON, it's also very easy to use. I'm using it in conjunction with ASIHTTPRequest.
Here's a quick modification of my code to relate to your question.
- (IBAction)getImages{
NSURL *url = [NSURL URLWithString:#"www.bbc.com/jsonoutput"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request{
NSError *error;
NSDictionary *bbcData = [[CJSONDeserializer deserializer] deserializeAsDictionary:[request responseData] error:&error];
//TODO: do something with the error
NSArray *images = [bbcData objectAtIndex:#"images"];
NSLog(#"%#", images);
}
- (void)requestFailed:(ASIHTTPRequest *)request{
NSError *error = [request error];
//TODO: do something with the error
}
https://github.com/stig/json-framework It's super easy to use. If you get stuck just look at how I used it in my code here
json-framework is good use it.