We've tried numerous times sending update PUT requests to our Rails server and we keep receiving a 404 "The page you were looking for does not exist"
Our update method is very simple (practically generic rails).
def update
@user = User.find(params[:id])
respond_to do |format|
if @user.update_attributes(params[:user])
format.html { redirect_to @user, notice: 'User was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
When I run CURL from the command line to test the update method, it works fine. But, when I try the same methods in objective-c, it always results in a 404 error.
So my question is: can iOS devices send PUT requests to servers using NSURLConnection or is this not implemented?
UPDATE::
This doesn't update the database
NSString *dataString = @"user[first_name]=bob";
NSData *postBodyData = [NSData dataWithBytes: [dataString UTF8String] length:[dataString length]];
NSString *urlString = [NSString stringWithFormat:@"example.com/users/1.json"];
NSURL *fullURL = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:fullURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20];
[request setHTTPMethod: @"PUT"];
[request setHTTPBody:postBodyData];
self.todoConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
receivedData = [NSMutableData data];
This updates the database
NSString *urlString = [NSString stringWithFormat:@"example.com/users/1.json?user[first_name]=bob"];
NSURL *fullURL = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:fullURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20];
[request setHTTPMethod: @"PUT"];
self.todoConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
receivedData = [NSMutableData data];
Actually @akshay1188 has a workable solution, but I think the more elegant approach is to add the "application/x-www-form-urlencoded" content type to the request:
[request setHTTPMethod:@"PUT"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
You can make an NSMutableURLRequest and set the HTTP method:
- (void)setHTTPMethod:(NSString *)method
Give it the string @"PUT"
.
Here is how you can create an NSURLConnection from such a request.
NSMutableURLRequest *myMutableRequest[[NSMutableURLRequest alloc] initWithURL:myURL];
[myMutableRequest setHTTPMethod:@"PUT"];
[NSURLConnection connectionWithRequest:myMutableRequest delegate:myDelegate];
Set the HTTP method type as @"POST"
And add a parameter to the request body as: @"PUT" for key @"_method"
It should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With