GET and POST requests from ios5 - iphone

I'm working on making a client for my REST service on the iPhone. I'm a little lost as to how I go about making the GET and POST requests. I make the url from a NSString, convert it to an NSURL and create the NSURLRequest based off of the url. After that I'm pretty lost. Also, sometimes I care about the response, other times I don't. For example, when making a request for a new id, I care about the response because it's the id I'll use to upload my file later, but when I upload the file I don't care because the server doesn't send a response.


Does anyone have some (hopefully)simple sample code that they could point me to / share?

What I have so far:
-(NSString *) makeGetRequest:(NSString *)url :(Boolean)careAboutResult
{
NSString *results = nil;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSError *reqError;
NSURLResponse *response = nil;
if(careAboutResult == YES)
{
//get the result
}
return results;
}

In the code I'm testing with, the URL is
http://192.168.0.108:8081/TestUploadService/RestfulUpload.svc/id/test123_DOT_png
and I'm saying I do care about the result.

Any help would be greatly appreciated.

#nick its good you have created a NSURLRequest now you just need to create a connection to send this request and receive response, this request is GET request.
To make POST request you will need to use NSMutableURLRequest and set its method name and body content. Here in documentation you will find how you can do this.

Related

Facebook iOS SDK 3.0, implement like action on a url?

I'm trying to implement Like via the facebook open-graph-api with the Facebook iOS SDK 3.0.
Everything seems to work except the FbGraphObject and that's because I have no idea how it should look because this clearly does not work.
What I'm trying to do is to like a url posted as an object. A simple Like with via the open-graph.
The error message I get the the code below is:
The action you're trying to publish is invalid because it does not specify any
reference objects. At least one of the following properties must be specified: object.
The code I use is this:
FBGraphObject *objectToLike = [[FBGraphObject alloc]initWithContentsOfURL:[NSURL URLWithString:facebookLike.titleLabel.text]];
FBRequest *requestLike = [[FBRequest alloc]initForPostWithSession:[FBSession activeSession] graphPath:#"me/og.likes" graphObject:objectToLike];
FBRequestConnection *connection = [[FBRequestConnection alloc] init];
[connection addRequest:requestLike
completionHandler:
^(FBRequestConnection *connection, id result, NSError *error) {
if (!error &&
result) {
DLog(#"NothingWentWrong");
}
DLog(#"MajorError: %#", error);
}
];
[connection start];
UPDATE:
Checked some more info and my guess it to use this method:
https://developers.facebook.com/docs/sdk-reference/iossdk/3.0/class/FBGraphObject/#//api/name/graphObject
To somehow create an object. It's the graphObject method that I probably need to do something with. Any help at all would be appreciated.
I've actually manage to create a simple and quite dirty solution of this.
The solution does not seem optimal but it's currently a working solution.
If anybody has used the explorer tool on facebook on this url:
https://developers.facebook.com/tools/explorer/
You know how the URL will look like when facebook is sharing a like. It has to have the URL and an access-token.
So my solution became just to disregard sending anything from the Facebook SDK and just send a post request to the same URL that I've used in the explorer tool.
There seems to be some referencing to it on the facebooks docs if you look closely and deep, but no one explains exactly how to actually make the connection, so this is my solution:
NSString *urlToLikeFor = facebookLike.titleLabel.text;
NSString *theWholeUrl = [NSString stringWithFormat:#"https://graph.facebook.com/me/og.likes?object=%#&access_token=%#", urlToLikeFor, FBSession.activeSession.accessToken];
NSLog(#"TheWholeUrl: %#", theWholeUrl);
NSURL *facebookUrl = [NSURL URLWithString:theWholeUrl];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:facebookUrl];
[req setHTTPMethod:#"POST"];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&err];
NSString *content = [NSString stringWithUTF8String:[responseData bytes]];
NSLog(#"responseData: %#", content);
If you look at the code I just take the url and puts two dynamic strings in the url, one with the object-url and one with the access token. I create a URLRequest and make it a POST request, and the response from facebook gets logged so one actually can see if the like go through or not.
There might be some performance improvements that can be done with the actual requests but I will leave it up to you if you see any slowdowns.
I'm still interested in other solutions but this is the one I will use for now.
We don't currently support Like through our Graph API.
What you can look through is something like this :
https://developers.facebook.com/docs/opengraph/actions/builtin/likes/
I’m not sure what initWithContentsOfURL does, but from the name I guess it tries to actually load content from a given URL(?).
You only have to give the URL as a text parameter – a URL is what represents an Open Graph object. Facebook will do the rest, scraping the page behind that URL and reading it’s OG meta tags, etc.
Maybe just this?
FBRequest *requestLike = [[FBRequest alloc]initForPostWithSession:[FBSession activeSession]
graphPath:#"me/og.likes"
graphObject:[NSURL URLWithString:facebookLike.titleLabel.text]];

when is a response code received during a request for an image using ASIHTTPRequest?

When do I actually get my response code 200 for a valid request for an image? Is it after all of the data has been downloaded to my browser or which ever device is requesting the image?
I am using the library http://allseeing-i.com/ASIHTTPRequest/ to download images in my iPad app and using the download directly to a file option and then deleting the file if it was a 404 error or any other status code than 200.
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadDestinationPath:#"/Users/ben/Desktop/my_file.jpg"];
Problem is partial responses seem to be getting saved during slow connections so I end up with blank or corrupt images.
I decided instead to save the data stream to disk only after I received a status code of 200:
NSURL *url = [NSURL URLWithString: [[NSString stringWithFormat:kProductImagesURL, fileName] stringByAppendingString:tStamp]];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setTimeOutSeconds:10];
[request startSynchronous];
int statusCode = [request responseStatusCode];
if (statusCode==200) {
NSData *responseData = [request responseData];
[responseData writeToFile:[savePath stringByReplacingOccurrencesOfString:#"%20" withString:#" "] atomically:YES];
}
I just want to make sure that the response code only comes back after the request has been completed and all of the data has been downloaded. I am 99% sure that is the case but can't afford another app release with an image bug like this in it.
There are two reasons you should probably consider switching to an asynchronous request. The first is, it frees up your main thread to interact with the user (even a modal spinner would be nice--otherwise it looks like your app has frozen).
Second, it gives you callbacks that only happen once the whole request is finished. I can't really explain only having gotten partial data with the code you showed, but I've never once had that problem using ASI's asynchronous methods.

Download and parse HTML without displaying it

I have just read different stuff about NSXMLParser, NSURLConnection, WebKit and more, but I don't know how to do this: I have a URL to a website and I would like to get the source of this website to read and later store relevant information.
Some guidance to the right direction would be appreciated, Fabian
To get your HTML, all you have to do is use a NSURLRequest to make a request to your website, then use the NSURLConnection to issue the request, this will return with some data that is the html source, from there you can do what you wish. I am going to post an example of how to make a request synchronously, just be aware that you probably want to do this async...Also here is a ref to NSURLRequest
NSURL *yourURL = [NSURL URLWithString: urlstring ];
NSURLRequest *request=[[NSURLRequest alloc] initWithURL:yourUrl];
NSData* data=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//now you can use the data and the websites encoding to get a string

Twitter profile image upload in objective-c

I want to upload an image to my twitter profile using objective-c. I saw in the twitter API that I need to send a HTML post to http://twitter.com/account/update_profile_image.format and send the picture as a parameter. I am done with the authentication. I am stuck with the uploading. Maybe somebody can help me with sending the picture as a parameter?
You should be using NSURLRequests and NSURLConnection to perform the API requests. If this is true, all you need to do is create an NSMutableURLRequest, set it's URL to the Twitter image upload API URL, set the method to POST.
Then you'll need to create an NSData object to represent your image, which you can do using
NSData *myImageData = [[NSData alloc] initWithData:[myImage CGImage]];
I don't know what the parameter name is for Twitter's upload API, so for arguments sake, lets call it "image". The next thing you need to do is set the image data as the request's body for the "image" parameter, like this
NSString *bodyString = [NSString stringWithFormat:#"image=%#", [[[NSString alloc] initWithData:myImageData encoding:NSStringUTF8Encoding] autorelease]];
[myRequest setBody:bodyString];
Then you can just start your NSURLConnection with the request and it should upload.
If you’ve managed to get started, then this post on CocoaDev should help you set the uploading up. There’s a sample linked at the top too.
I recommend using ASIHTTPRequest
What is ASIHTTPRequest?
ASIHTTPRequest is an easy to use wrapper around the CFNetwork API that makes some of the more tedious aspects of communicating with web servers easier. It is written in Objective-C and works in both Mac OS X and iPhone applications.
It is suitable performing basic HTTP requests and interacting with REST-based services (GET / POST / PUT / DELETE). The included ASIFormDataRequest subclass makes it easy to submit POST data and files using multipart/form-data.
See this blog post for an example
Somthing like this
// See http://groups.google.com/group/twitter-development-talk/browse_thread/thread/df7102654c3077be/163abfbdcd24b8bf
NSString *postUrl = #"http://api.twitter.com/1/account/update_profile_image.json";
ASIFormDataRequest *req = [[ASIFormDataRequest alloc] initWithURL:[NSURL
URLWithString:postUrl]];
[req addRequestHeader:#"Authorization" value:[oAuth oAuthHeaderForMethod:#"POST"
andUrl:postUrl andParams:nil]];
[req setData:UIImageJPEGRepresentation(imageView.image, 0.8)
withFileName:#"myProfileImage.jpg"
andContentType:#"image/jpeg" forKey:#"image"];
[req startSynchronous];
NSLog(#"Got HTTP status code from Twitter after posting profile image: %d", [req
responseStatusCode]);
NSLog(#"Response string: %#", [req responseString]);
[req release];

iPhone: Post data to php page

Despite looking at similar posts on this site and google, I just can't wrap my head around how to post to a php page from the iPhone. Here is what I want to do:
I have a php script, say at www.mypage.com/myscript.php that I could post to normally by doing www.mypage.com/myscript.php?mynumber=99&myname=codezy
This in turn will add a log message in database for example. I do not want any data back, it is essentially a one way transaction. NSMutableURLRequest seems to be what I am looking for but I just cant get a handle on how to make this work with a couple parameters.
If you're sending a single URL request without needing to send multiple variations, NSURLRequest will do. Even though you are using multiple parameters, they are all part of the same URL, so you just treat them that way. Build the URL as a string first and then use the string to initialize a NSURL object.
You are prompting a log message on the server, but you will want to have response data in case something goes wrong. You can just ignore the response data unless there's an error. The request is sent using a NSURLConnection object.
NSURL *urlToSend = [[NSURL alloc] initWithString: #"www.mypage.com/myscript.php?mynumber=99&myname=codezy"];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:urlToSend
cachePolicy:NSURLRequestReturnCacheDataElseLoad
cachetimeoutInterval:30];
NSData *urlData;
NSURLResponse *response;
NSError *error;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];