I am trying to upload video file to the specified URL. When I press button video file should upload into the URL which I used. But no response is coming.
NSString *filePath = [[NSBundle mainBundle]pathForResource:#"3idiots" ofType:#"mov"];
NSURL *uploadurl=[NSURL URLWithString:#"http://115.111.27.206:8081/vblo/upload.jsp"];
//NSData *postVideoData = [NSData dataWithContentsOfFile:filePath];
NSData *postVideoData = [string dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postVideoLength = [NSString stringWithFormat:#"%d", [postVideoData length]];
NSMutableURLRequest *request12 = [[[NSMutableURLRequest alloc] init] autorelease];
[request12 setURL:uploadurl];
[request12 setHTTPMethod:#"POST"];
[request12 setValue:postVideoLength forHTTPHeaderField:#"Content-Length"];
[request12 setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request12 setHTTPBody:postVideoData];
NSURLConnection *theConnection12 = [[NSURLConnection alloc] initWithRequest:request12 delegate:self];
if( theConnection12 )
{
webData12 = [[NSMutableData data] retain];
}
else
{
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData12 setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData12 appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *loginStatus12 = [[NSString alloc] initWithBytes: [webData12 mutableBytes] length:[webData12 length] encoding:NSUTF8StringEncoding];
NSLog(loginStatus12);
if(loginStatus12)
{
UIAlertView *statusAlert12 = [[UIAlertView alloc]initWithTitle:nil message:(NSString *)loginStatus12 delegate:self cancelButtonTitle:#"cancel" otherButtonTitles:nil];
[statusAlert12 show];
}
}
you need to send the request, add this line after you set the HTTPBody
NSData *serverReply = [NSURLConnection sendSynchronousRequest: request12 returningResponse:&response error:&error];
Related
I have a web service I am working with a url such as
//myurl/index.jsp?user_name=bob&user_pwd=new
as you can see the username has been set as "bob" and password "new". The site give this json file when entered,
[{"success":"1"}]
How do you implemented it on xcode, where when a user enters "bob" as username and "new" as password it should lead to the next controller. How do can I achieve that ?
I followed this tutorial though it's not quite the same, how do you do this. Thanks.
Use a navigation controller and set you view controller as the rootViewController. Then after the user has entered the credentials push the new view controller onto the navigation stack.
Get the value of success from json response. If it is equal to 1 then push to next controller else do nothing.
In Following code you can pass data by either GET or POST method … use any one (As You Wish)
-(void) sendRequest
{
//////////////////////////// GET METHOD /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
NSString *strURL=[NSString stringWithFormat:#"http://myurl/index.jsp?user_name=bob&user_pwd=new"];
self.request=[NSURLRequest requestWithURL:[NSURL URLWithString:strURL]];
self.nsCon=[[NSURLConnection alloc] initWithRequest:request delegate:self];
//////////////////////////// POST METHOD /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
NSString *postString = [NSString stringWithFormat:#"&user_name=bob&user_pwd=new"];
NSString *url = [NSString stringWithFormat:#"http://myurl/index.jsp/"];
self.request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[self.request setHTTPMethod:#"POST"];
[self.request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if(self.nsCon)
{
self.receivedData=[[NSMutableData alloc] init];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Error",#"") message:NSLocalizedString(#"Not Connected !!",#"") delegate:nil cancelButtonTitle:NSLocalizedString(#"OK",#"") otherButtonTitles:nil];
[alert show];
[alert release];
}
}
#pragma mark -
#pragma mark - Connection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[GeneralClass stopHUD];
NSLog(#"Connection failed.");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Error",#"") message:NSLocalizedString(#"Connection failed!",#"") delegate:nil cancelButtonTitle:NSLocalizedString(#"OK",#"") otherButtonTitles:nil];
[alert show]; alert = nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
NSMutableDictionary *receivedData = [responseString JSONValue];
if([[receivedData objectForKey:#"success"] isEqualToString:#"1"])
{
MainDetailViewController *mdController = [[MainDetailViewController alloc] init];
[self.navigationController pushViewController:mdController animated:YES];
}
else
{
NSLog(#"%#",receivedData);
}
}
Post login data
NSString *soapMsg = [NSString stringWithFormat:#"&data={\"LoginUser\":[{\"UserName\":\"%#\",\"Password\":\"%#\"}]}",firstname.text, password.text];
NSHTTPURLResponse *response;
NSData *myRequestData = [ NSData dataWithBytes: [ soapMsg UTF8String ] length: [ soapMsg length ] ];
NSString *postLength = [NSString stringWithFormat:#"%d", [myRequestData length]];
NSMutableURLRequest *request = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString:#"http://myurl/index.jsp"]];
[request setHTTPMethod: #"POST" ];
[request setHTTPBody: myRequestData ];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: myRequestData];
NSURLConnection *myConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
Receive and vaild json data
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:WebXmlData encoding:NSUTF8StringEncoding];
NSDictionary *results = [responseString JSONValue];
BOOL success = [[results objectForKey:#"success"] boolValue];
if (success) {
ViewController *viewController =[[ViewController alloc]initWithNibName:#"ViewController" bundle:nil];
[self.navigationController pushViewController:viewController animated:YES];
}
}
Not quite the answer you are looking for but this is more a recommendation for what should you use.
I use github link for Network related activities.
They have nice documentation and very easy to use (uses blocks)
NSDictionary *paramsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:#"user",#"client_id",#"password",#"new", nil];
[[YourAFHttpClientExtenstion sharedInstance] postPath:LOGIN_PATH parameters:paramsDictionary success:^(AFHTTPRequestOperation *operation, id responseObject) {
//handle success
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// handle error.
}];
YourAFHttpClientExtenstion is extending AFHttpClient and adds a convening method of shared instance and implements initWithBaseUr:
I am new in objective C. I have done app in j2me and android using below code. I m trying same to consume web service through objective C but not getting success. It will be great if anyone guide me.
Thanks.
public static String RetriveData(String myStr)
{
String result1 = "-1";
Object ob1 = new Object();
ob1 =MyStr;
SoapObject rpc = new SoapObject("http://abcd.com/", "MyMethod");
rpc.addProperty("Mystr", ob1.toString());
try
{
Object strdata = new HttpTransport("http://11.22.33.44/myService.asmx", "http://abcd.com/" + "MyMethod").call(rpc);
result1 = strdata.toString().trim();
}
catch (Exception ex)
{
System.out.println("In catch block :" +ex);
}
return result1;
}
I am trying same through objective C as below but getting error.
NSURL *url = [NSURL URLWithString:#"http://11.22.33.44/MyService.asmx"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
//
//[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"http://abcd.com/MyMethod" forHTTPHeaderField:#"SOAPAction"];
//[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest addValue:#"MyStr" forHTTPHeaderField:#"MyStr"];
[theRequest setHTTPMethod:#"POST"];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
webData = [[NSMutableData data] retain];
}
else
{
NSLog(#"theConnection is NULL");
}
[nameInput resignFirstResponder];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"ERROR with theConenction");
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"DONE. Received Bytes: %d", [webData length]);
NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:
[webData length] encoding:NSUTF8StringEncoding];
NSLog(theXML);
[theXML release];
if( xmlParser )
{
[xmlParser release];
}
xmlParser = [[NSXMLParser alloc] initWithData: webData];
[xmlParser setDelegate: self];
[xmlParser setShouldResolveExternalEntities: YES];
[xmlParser parse];
[connection release];
[webData release];
}
My personal recommendation is to use ASIHttpRequest. I consume web services (both .NET and PHP) with it and it seems much easier and straightforward to use in most cases.
Just include the ASIHttpRequest classes and the MBProgressHUD (If you want to use it)
Here is what I use to do it:
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.labelText = #"Connecting to Server";
// Start request
NSURL *url = [NSURL URLWithString:#"http://mydomain/MyWebService.asmx/MyMethod"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setValidatesSecureCertificate:NO];
// Now setup the Request
[request setPostValue:#"MyValue1" forKey:#"WebServiceArg1"];
[request setPostValue:#"MyValue2" forKey:#"WebServiceArg2"];
[request setDelegate:self];
[request startAsynchronous];
Now use the delegate methods to check and consume the response from the web service:
#pragma mark - ASIHttpRequest Delegate Methods
- (void)requestFinished:(ASIHTTPRequest *)request
{
[MBProgressHUD hideHUDForView:self.view animated:YES];
if (request.responseStatusCode == 200) {
NSString *responseString = [request responseString];
// Do something with this, create an array or dictionary depending on how the return data is structured (this assumes you are using a JSON formatted return string btw
}
else {
// Standard UIAlert Syntax
UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:#"Connection Error"
message:#"My Message"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[myAlert show];
}
} else {
NSLog(#"Error finishing request");
}
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
[MBProgressHUD hideHUDForView:self.view animated:YES];
// Standard UIAlert Syntax
UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:#"Connection Error"
message:#"Unable to establish connection"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[myAlert show];
NSError *error = [request error];
NSLog(#"%#",error.localizedDescription);
}
There are many ways to do it but this is what I would use.
I am updating my data but it not updating why it happen
i want if any register user want to change data old to new then i give a update page where the user change there data but except username i try lot byt it's not updata data to server databasetable my cod is proper or wrong
-(void)sendRequest
{
NSString *post = [NSString stringWithFormat:#"firstname=%#&lastname=%#&Username=%#&Password=%#&Email=%#",txtfirstName.text,txtlast.text,txtUserName.text,txtPassword.text,txtEmail.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"%#",postLength);
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://192.168.0.1:96/JourneyMapperAPI?RequestType=Register&Command=SET"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
NSLog(#"%#",webData);
}
else
{
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSLog(#"%#",loginStatus);
}
you need to start the connection:
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
NSLog(#"%#",webData);
[theConnection start];
}
else
{
}
How to make Http Post Request using JSON. I tried every option which is available on Internet.But could not get the Data. So please post entire code to make a request.
You can use below code:
-(void)performRequest{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"url"]];
NSString *msgLength = [NSString stringWithFormat:#"%d", [jsonMessage length]];
[request addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request addValue: jsonAction forHTTPHeaderField:#"JSONAction"];
[request addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: [jsonMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if( theConnection )
{
webData = [[NSMutableData data] retain];
}
else
{
NSLog(#"theConnection is NULL");
}
[pool release];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[webData setLength: 0];
self.resultArray = [[NSMutableArray alloc] init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(#"ERROR with theConenction");
NSDictionary *errorDic = [NSDictionary dictionaryWithObject:error forKey:#"error"];
[self.resultArray addObject:errorDic];
[connection release];
[webData setLength:0];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(#"DONE. Received Bytes: %d", [webData length]);
NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSLog(#"%#", theXML);
[theXML release];
if([webData length] > 0){
parser = [[NSXMLParser alloc] initWithData:webData];
[parser setDelegate:self];
[parser parse];
}
}
Here's a basic example of NSURLConnection POST-ing JSON to an URL.
- (void)performRequest {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://someplace.com/"]];
[request setValue:#"Some Value" forHTTPHeaderField:#"Some-Header"];
[request setHTTPBody:#"{\"add_json\":\"here\"}"];
[request setHTTPMethod:#"POST"];
[NSURLConnection connectionWithRequest:[request autorelease] delegate:self];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// Fail..
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// Request performed.
}
I'm planning to convert my website into an iPhone native application. I'm stuck at the point of how to achieve this.
Initially, I have developed the first screen i.e., LOGIN screen of my application. My server is built in Java. I'm able to send the login credentials to the server and able to see the request on the server. But I'm unable to receive the response from the server for the request I've sent.
A part of my code is:
NSString *post = #"username=";
post = [post stringByAppendingString:username];
post = [post stringByAppendingString:#"&password="];
post = [post stringByAppendingString:password];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://mysite.com/login.action?"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// [request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn)
{
receivedData = [[NSMutableData data] retain];
NSLog(#"In \"LOGIN()\" : receivedData = %#",receivedData);
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[receivedData setLength:0];
NSLog(#"In \"didReceiveResponse()\" : receivedData = %#",receivedData);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
NSString *ReturnStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"In \"didReceiveData()\" : receivedData = %#",receivedData);
NSLog(#"Return String : %#", ReturnStr);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Succeeded! Received %d bytes of data",[receivedData length]);
NSString *urlData;
if (nil != receivedData) {
urlData = [[[NSString alloc] initWithData:receivedData
encoding:NSUTF8StringEncoding] autorelease];
}
NSLog(#"In \"connectionDidFinishLoading()\" : urlData = %#",urlData);
[receivedData release];
}
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error
{
[connection release];
[receivedData release];
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
}
How do I develop a LOGIN application?
I'm sending a request successfully to the server but I'm unable to get the response from the server. How can I overcome this issue?
If your experience is with web development you may be interested in looking at NimbleKit for iPhone. It's a simple XCode plugin that allows you to use HTML and JavaScript to develop the entire native application.