ASIHTTPRequest UIWebView load documents - iphone

What is the best way to view documents (pdf,doc,xls) using AsiHttpRequest and UIWebView??? I tried the following, but the UIWebView is displaying the html:
NSString * baseURL = #"http://xxxxxx/open-api/v1/";
NSString * itemRef = #"item/133/attachment/test.pdf";
NSString *urlString = [NSString stringWithFormat:#"%#%#", baseURL, itemRef];
NSURL *url = [NSURL URLWithString:urlString];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setUsername:#"xx"];
[request setPassword:#"xx"];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
[self.webView loadHTMLString:[request responseString] baseURL: [request url]];
}
else {
NSLog(#"Error: %#", error );
}
AsiHttpRequest is required for setting Basic Authentication and Header Values... Thanks!

Well, to be fair, you're telling it to display HTML, so the result isn't really unexpected :-)
You'd need to download the pdf file locally:
NSString *tmpLocation = // some temporary file location
[request setDownloadDestinationPath:tmpLocation]];
[request startSyncronous];
then view it in UIWebView:
NSURL *url = [NSURL fileURLWithPath:tmpLocation];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];

Related

Post Data but GET Method json -ios

how can i use the get method to post data on an api link with 6 values and a json format?
im really fuzzled. im doing this for days . is it best to have 6 textfields that will be used to write the value and a button to indicate post data?
check out my code and please help.
-(IBAction)postDataPressed
{
NSString *urlString = #"http://192.168.18.8/apisample2/friendb.php?fm=jsn";
NSURL *url = [NSURL URLWithString:urlString];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:user.text forKey:#"un"];
[request setPostValue:pass.text forKey:#"pd"];
[request setPostValue:gender.text forKey:#"gd"];
[request setPostValue:age.text forKey:#"ag"];
[request setPostValue:status.text forKey:#"st"];
[request setPostValue:lookfor.text forKey:#"lf"];
[request setRequestMethod:#"GET"];
[request setCompletionBlock:^{
NSString *responseString = [request responseString];
NSLog(#"Response: %#", responseString);
}];
[request setFailedBlock:^{
NSError *error = [request error];
NSLog(#"Error: %#", error.localizedDescription);
}];
[request setDidFinishSelector:#selector(requestFinished:)];
[request setDidFailSelector:#selector(requestFailed:)];
[request startAsynchronous];
}
i hope someone will help.
NSString *request_url = [NSString stringWithFormat: #"http://192.168.18.8/apisample2/friendb.php?fm=jsn&un=%#&pd=%#&gd=%#&ag=%#&st=%#&lf=%#",
user.text, pass.text, gender.text, age.text,status.text,lookfor.text];
NSURL *url = [NSURL URLWithString:request_url];
ASIHttpRequest *request = [ASIHttpRequest requestWithURL:url];
request.delegate = self;
....
HTTP Get method only accept data in url, called query string, so you have to build query string yourself.

Post image to facebook using graph api

I am using facebook graph api to post image and message to facebook. I have taken help from Raywenderlich tutorial. It was working fine before last two weeks. But now it creating issue for me. I am getting all the facebook profile information.
UIImage *image = [UIImage imageNamed:#"no_image.png"];
data = UIImagePNGRepresentation(image);
NSURL *url = [NSURL URLWithString:#"https://graph.facebook.com/me/photos"];
NSString *message = [couponInfoDictionary objectForKey:#"offerTitle"];
message = [message stringByAppendingString:#"\n"];
NSString *offerSlogan = [couponInfoDictionary objectForKey:#"offerSlogan"];
message = [message stringByAppendingString:[NSString stringWithFormat:#"%#",offerSlogan]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setData:data forKey:#"file"];
[request setPostValue:message forKey:#"message"];
[request setPostValue:_accessToken forKey:#"access_token"];
[request setDidFinishSelector:#selector(sendToPhotosFinished:)];
[request setDidFailSelector:#selector(requestError:)];
[request setDelegate:self];
[request startAsynchronous];
- (void)sendToPhotosFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
NSLog(#"response string before photo id %#",responseString);
NSMutableDictionary *responseJSON = [responseString JSONValue];
NSString *photoId = [responseJSON objectForKey:#"id"];
NSLog(#"Photo id is: %#", photoId);
NSString *urlString = [NSString stringWithFormat:#"https://graph.facebook.com/%#?access_token=%#", photoId, [_accessToken stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"sendToPhotosFinished = %#",urlString);
NSURL *url = [NSURL URLWithString:urlString];
ASIHTTPRequest *newRequest = [ASIHTTPRequest requestWithURL:url];
[newRequest setDidFinishSelector:#selector(getFacebookPhotoFinished:)];
[newRequest setDelegate:self];
[newRequest startAsynchronous];
}
But when i posting the image, It giving me error
{"error":{"message":"Error validating application.","type":"OAuthException"}}
Photo id is: (null)
sendToPhotosFinished = https://graph.facebook.com/(null)?access_token=ABACesEZBKr3gBALqa4yE2QAnJbNbGvQKa9iCm53GmTwHQYoyaxqAqmdLj0gw9uWCbyhP5sV7N6uZBjaFDpD6v6G1C7GcZCjvcZBPqt7b1ZAxKtDvepN8c&expires_in=4778
Got Facebook Photo: {"error":{"message":"(#803) Some of the aliases you requested do not exist: (null)","type":"OAuthException"}}
I have spent my three days to resolve it. But still not getting any idea..how to solve this?
use this #"117795728310/photos" insted of me/photos
In the third line of your above code ,
Photo id is: (null)
2012-02-16 11:59:11.298 FBFun[2330:207] Got Facebook Photo:
{
"error": {
"message": "(#803) Some of the aliases you requested do not exist: (null)",
"type": "OAuthException",
"code": 803
}
}
I have used following code, and it is working...
NSURL *url = [NSURL URLWithString:#"https://graph.facebook.com/USER_FACEBOOK_PROFILE_ID/photos"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"img1" ofType:#"jpg"];
nsstring *accessToken = #"AAACWZA..............................................Ts28iSOhGoOhe9qAgpZCL7AZDZD";
[request addData:[[NSUserDefaults standardUserDefaults]dataForKey:#"image1"] forKey:#"file"];
[request setPostValue:#"Testing App For iPhone, please don't comment..." forKey:#"message"];
[request setPostValue:accessToken forKey:#"access_token"];
[request setDelegate:self];
[request startAsynchronous];

Is there any way to cache ASIFormDataRequest?

I'm using ASIFormDataRequest for Post data then parsing with JSON. ASIHTTPRequest has built in caching using [ASIHTTPRequest setDefaultCache:[ASIDownloadCache sharedCache]];. Does anyone know if there is anything similar for ASIFormDataRequest?
Example:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/myapp/20110715/60b88126/load_dr_daily_schedule/%#/", [self getHost], [dateFormat stringFromDate:today]]];
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[self addCurrentUserLoginToPostRequest:request];
[request setPostValue:[dateFormat stringFromDate:today] forKey:#"target_date"];
[request startSynchronous];
NSError *error = [request error];
NSString *responseString;
if (!error) {
responseString = [request responseString];
} else {
return NULL;
}
return [responseString JSONValue];
ASIFormDataRequest is a subclass of ASIHTTPRequest, so it was the same properties as ASIHTTPRequest.
Note that it won't cache POST requests though.

Synchronous ASIHTTPRequest updating label

It seems very simple but not easy for me.. I am calling a few Synchronous ASIHTTPRequests and when each request is finished, I want to update a Label like following..
self.status.text = #"Google";
NSURL *url = [NSURL URLWithString:#"http://www.google.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
self.status.text = #"Yahoo";
NSURL *url = [NSURL URLWithString:#"http://www.yahoo.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
self.status.text = #"Apple";
NSURL *url = [NSURL URLWithString:#"http://www.Apple.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
However, it only show nothing but "Apple" once all calls are done.. What is the simple and best way to achieve this?
UIKit has no chance to redraw the label because you're blocking the main thread for the whole url request.
You should use asynchronous requests instead, so the UI will be responsive all the time. Also update the UI in a completion block:
self.status.text = #"Google";
NSURL *url = [NSURL URLWithString:#"http://www.google.com"];
__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setCompletionBlock:^{
self.status.text = #"Yahoo";
// start another request etc.
}];
[request startAsynchronous];

Problems with using POST from iPhone to REST service

I'm building an iPhone client that will GET and POST to a REST service.
The GET-part works fine, but I don't seem to be able to POST anything. The server only accepts xml at the moment.
I've tried to use ASIHTTPRequest, ASIFormDataRequest and doing it myself but nothing seems to work.
Can anyone help me? I'm fairly new to Objective-C programming.
I do get a status code: 200 as a response using the following code in didReceiveResponse:
NSHTTPURLResponse * httpResponse;
httpResponse = (NSHTTPURLResponse *) response;
int myStatus = httpResponse.statusCode;
if (myStatus == 400) {
NSLog(#"Status code: 400");
} else if (myStatus == 200) {
NSLog(#"Status code: 200");
} else {
NSLog(#"Other status code");
Here follows three different approaches...
Code (ASIHTTPRequest):
NSURL *url = [NSURL URLWithString:#"myUrl.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request appendPostData:[#"<my xml>" dataUsingEncoding:NSUTF8StringEncoding]];
// Default becomes POST when you use appendPostData: / appendPostDataFromFile: / setPostBody:
[request setRequestMethod:#"POST"];
[request setDelegate:self];
[request startSynchronous];
Code (ASIFormDataRequest):
NSURL *url = [NSURL URLWithString:#"someUrl.com"];
ASIFormDataRequest *theRequest = [ASIFormDataRequest requestWithURL:url];
// [theRequest setPostValue:#"" forKey:#"key1"];
[theRequest setPostValue:#"90" forKey:#"key2"];
[theRequest setPostValue:#"150" forKey:#"key3"];
// [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:TRUE];
[theRequest startAsynchronous];
Code (Third method):
NSData *myPostData = [[NSString stringWithFormat:#"<my xml>"] dataUsingEncoding:NSUTF8StringEncoding];//NSASCIIStringEncoding];
// NSString *xmlPostData = #"<my xml>";
NSURL *theURL = [NSURL URLWithString:#"someUrl.com"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-type"];
// [theRequest setValue:#"UTF-8" forHTTPHeaderField:#"Charset"];
[theRequest setHTTPBody:myPostData];// [xmlPostData dataUsingEncoding:NSUTF8StringEncoding]];// myPostData];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:TRUE];
How about all these -(void)connection: style functions? Does any of them have to contain specific code for the connection to work?
Many thanks for any help!
NSURL *url = [NSURL URLWithString:#"http://myURL.com"];
ASIHTTPRequest *request = [ASIFormDataRequest requestWithURL:url];
NSData *myPostData = [[NSString stringWithFormat:#"<My XML Body>"] dataUsingEncoding:NSUTF8StringEncoding];//NSASCIIStringEncoding];
NSMutableData *myMutablePostData = [NSMutableData dataWithData:myPostData];
[request addRequestHeader:#"Content-Type" value:#"application/xml"];
[request setPostBody:myMutablePostData];
[request setDelegate:self];
[request startSynchronous];