Progress Bar With NSURLConnection - ios

I want to show the progress bar while downloading a video from an url. I'm not able to figure out where I have gone wrong,and also expectedContentLength is always showing -1. Here is the code.
-(void)getResource{
bytesReceived = 0;
self.progressView.progress = 0.0;
NSString *string = #“MY_URL";
NSMutableURLRequest *request =[[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:string]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
self.feedConnection = [[NSURLConnection alloc]initWithRequest:request delegate:self]
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
self.responseData = [NSMutableData data];
[self.responseData setLength:0];
float length = [response expectedContentLength];
expectedBytes = [NSNumber numberWithUnsignedInteger:length];
NSLog(#"expected bytes %f %#",length,expectedBytes);
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.responseData appendData:data];
float progress = (float)[self.responseData length]/[expectedBytes floatValue];
NSLog(#"%f / %f is %f", (float)[self.responseData length] ,[expectedBytes floatValue],progress);
self.progressView.progress = progress;
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
self.feedConnection = nil;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
self.feedConnection = nil;
[self.view setBackgroundColor:[UIColor blackColor]];
[self fetchedData:self.responseData];
self.responseData = nil;
}

I think,you Can use NSURLConnectionDownloadDelegate method in which will get the totalBytes and how much data has been downloaded.
- (void)connection:(NSURLConnection *)connection
didWriteData:(long long)bytesWritten
totalBytesWritten:(long long)totalBytesWritten
expectedTotalBytes:(long long) expectedTotalBytes;

Related

How do I convert NSData to NSDictionary using NSJSONSerialization?

Hi I am facing problem in conversion of NSData to NSDictionary using NSJSONSerialization?
I got data using my code but unable to convert it into json.
Here is my code...
ViewController.h File
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<NSURLConnectionDelegate>
{
NSString *massage;
NSURL *url;
NSMutableURLRequest *request;
NSURLConnection *connection;
NSMutableData *httpbody;
NSMutableData *webData;
NSData *responceData;
NSDictionary *responceJson;
}
and ViewController.m File
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *mobile = #"123456789";
NSString *password = #"Welcome123";
NSString *deviceId = #"123sdfg15641ert321ret";
url = [NSURL URLWithString:#"http://203.109.87.34:8585/d-cab/web/app_dev.php/api/v1"];
massage = [NSString stringWithFormat:#"{\"action\":\"login\",\"data\":{\"contact\":\"%#\",\"password\":\"%#\",\"deviceId\":\"%#\"}}",mobile,password,deviceId];
//NSLog(#"Body = %#", massage);
httpbody = [ NSMutableData dataWithBytes: [ massage UTF8String ] length: [ massage length ] ];
request = [NSMutableURLRequest requestWithURL: url];
[request setHTTPMethod: #"POST"];
[request setHTTPBody: httpbody];
[request setTimeoutInterval:10.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
//NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
//[connection start];
if (connection) {
webData = [[NSMutableData alloc]init];
}
}
#pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[webData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[webData appendData:data];
//NSLog(#"WebData = %#",webData);
//NSLog(#"=================================");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSError* error = nil;
responceJson = [NSJSONSerialization JSONObjectWithData:webData options:kNilOptions error:&error];
NSLog(#"ResponceJSON = %#",responceJson);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// Show error message
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Error In connection" message:#"We are facing some problem in connection. Please Check your Internet Connection." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Please Check my code and tell me where and what change I have to make?
Hey Thanks to all who gave attention to my question.... But I found the problem in my question.
I am trying to send the parameter into string format instead of dictionary format and not specifying header to request. Here is my updated code...
NSDictionary *paramData = [[NSDictionary alloc]initWithObjectsAndKeys:mobile,#"contact",password,#"password",deviceId,#"deviceId", nil];
//NSLog(#"paramData = %#",paramData);
jsonParam = [[NSDictionary alloc]initWithObjectsAndKeys:#"login",#"action",paramData,#"data", nil];
//NSLog(#"jsonParam = %#",jsonParam);
httpbody = [NSJSONSerialization dataWithJSONObject:jsonParam options:0 error:nil];
request = [NSMutableURLRequest requestWithURL: url];
request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [httpbody length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: httpbody];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
webData = [[NSMutableData alloc]init];
}
It worked for me....
Try using the following code :
responceJson = [NSJSONSerialization JSONObjectWithData:webData
options:NSJSONReadingMutableContainers
error:&error];
Well the problem here is not in conversion problem is in this funtion
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
//[webData setLength:0];
webdData = [[NSMutableData alloc] init];
}
It will help.Thanks
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:request delegate:self];
if( theConnection )
{
mdata = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
mdata.length=0;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[mdata appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// Data store in dictionary when connection proceed in background
dict=[NSJSONSerialization JSONObjectWithData:mdata options:kNilOptions error:nil];
NSLog(#"%#",dict);
}
This is working gooood...
Try to check, what your connection is load. Converting NSData to NSString. In didFinishLoading typing this:
NSString *tempString = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSLog(#"loaded data: %#",tempString);

Login issues returns me previous login profile

I uses nsurlconnection delegates to post request I just created one class to test my login post request one I login it gives me correct profile and again I run and login with another credentials it is giving me previous profile I done understand what is the problem I am posting to ROR server
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[receivedData setLength:0];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError * error;
jsonDictionary = [NSJSONSerialization JSONObjectWithData:receivedData options:0 error:&error];
NSLog(#"%#",jsonDictionary);
theConnection = nil;
receivedData = nil;
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
theConnection = nil;
receivedData = nil;
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (IBAction)sigininAction:(id)sender {
if (theConnection) {
[theConnection cancel];
receivedData.data = nil;
jsonDictionary = nil;
theConnection = nil;
}
NSString *bodyData = [NSString stringWithFormat:#"user[email]=%#&user[password]=%#",[_email text],[_password text]];
NSData *postData = [bodyData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://URL/login"]];
[postRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[postRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[postRequest setHTTPMethod:#"POST"];
[postRequest setHTTPBody:postData];
theConnection=[[NSURLConnection alloc] initWithRequest:postRequest delegate:self];
if (theConnection) {
[theConnection start];
receivedData = [[NSMutableData alloc]init];
}
}

Login issue in IOS Application it is giving me same profile every time when ever i hits to the server

My project is almost finished but now login Screen is became a big issue the problem is for example i create a new project with one class and rights the Login Part only using NSURLConnectionDelegate Methods and run the project i am getting my profile in JSON format it is correct but now when i run again and not typing any thing in to the textfields and clicks the SIGNIN Button it is giving me same response i don't understand why is this happening can some one help me with this
This is the CODE
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[receivedData setLength:0];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError * error;
jsonDictionary = [NSJSONSerialization JSONObjectWithData:receivedData options:0 error:&error];
NSLog(#"%#",jsonDictionary);
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (IBAction)sigininAction:(id)sender {
NSString *bodyData = [NSString stringWithFormat:#"user[email]=%#&user[password]=%#",[_email text],[_password text]];
NSData *postData = [bodyData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://URL/login"]];
[postRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[postRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[postRequest setHTTPMethod:#"POST"];
[postRequest setHTTPBody:postData];
theConnection=[[NSURLConnection alloc] initWithRequest:postRequest delegate:self];
if (theConnection) {
[theConnection start];
receivedData = [[NSMutableData alloc]init];
}
}

how to GET responses when data post to URL

I know about how to post data (UITextField values) to JSON url using POST.But now i tried post Data using GET method to server.I have 10 textFields.I tried like this way
NSString *post1 =[NSString stringWithFormat:#"?&dealImage=%#&dealcatid=%#&DeaTitle=%#&DealDesc=%#&price=%#&cityId=%#&StartDate=%#&EndDate=%#&FromTime=%#&ToTime=%#",
strEncoded, string1 ,pTitle.text ,Description.text ,pPrice.text,string2,beginDate,endDate,beginTime,endTime];
NSData *postData = [post1 dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSLog(#"array array %#",postLength);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://192.168.3.125:8090/SaveDollar/rest/deals/add"]]];
NSLog(#"getData%#",request);
[request setHTTPMethod:#"GET"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
NSLog(#"getData%#",request);
con3 = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(con3)
{
webData3=[NSMutableData data];
NSLog(#"Connection successfull");
NSLog(#"GOOD Day My data %#",webData3);
}
else
{
NSLog(#"connection could not be made");
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if (connection ==con3)
{
[webData3 setLength:0];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
if (connection ==con3)
{
[webData3 appendData:data];
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
if (connection ==con3) {
NSLog(#"SOMETHING WENT WRONG WITH URL3");
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
if (connection==con3)
{ NSLog(#"Succeeded! Received %d bytes of data",[webData3 length]);
NSLog(#"Data is %#",webData3);
NSString *responseText = [[NSString alloc] initWithData:webData3 encoding: NSASCIIStringEncoding];
NSLog(#"Response: %#", responseText);//holds textfield entered value
NSString *newLineStr = #"\n";
responseText = [responseText stringByReplacingOccurrencesOfString:#"<br />" withString:newLineStr];
NSLog(#"ResponesText %#",responseText);
}
}
When after submit console will be show this message"SOMETHING WENT WRONG WITH URL3"
I know posting but now I need post Data and the Get Response also.So I used GET Method but i am not getting response.So Please give me any idea. And then Please tell me what wrong in my code.
Use the callback function
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
If the call is failing the error variable will help you see what is going wrong so you can figure it out yourself.
One thing which might help too is to set your request's content-type field to application/json.
you should collect response data like this:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
_responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[_responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// connection fail
}
where data is NSMutableData *_responseData;

NSURLConnection Delegate methods not getting called after two times

I am sending a request to server using NSURLConnection, it worked for 2 times , since third time it is not working, delegates are not being called. What i found during debugging is connectionShouldUseCredentialStorage method is called for initial times, third time it was not called and rest of methods are also not called.
Here is my code:
NSString *requestString = [NSString stringWithFormat:#"%#", [serviceParameters JSONFragment], nil];
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: strUrl]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-type"];
[request setHTTPBody:requestData];
[NSURLConnection connectionWithRequest:urlRequest delegate:self];
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.data = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)aData
{
[self.data appendData:aData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
SBJSON *jsonParser = [[SBJSON new] autorelease];
NSString *jsonString = [[[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding] autorelease];
NSError *outError = nil;
id result = [jsonParser objectWithString:jsonString error:&outError];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
{
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
}
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
if( [[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust] )
{
return YES;
}
return NO;
}
- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection
{
return YES;
}
in .h
NSMutableData * data;
NSURLConnection *connection;
Also add Add
in .m
-(void) startConnection
{
NSString *requestString = [NSString stringWithFormat:#"http://md5.jsontest.com/?text=Pushkraj"];
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestString]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
data = [NSMutableData dataWithCapacity:0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-type"];
[request setHTTPBody:requestData];
connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
data = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)aData
{
[data appendData:aData];
NSDictionary * dataDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSLog(#"dataDict : %#",dataDict);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"connectionDidFinishLoading");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Error : %#",error);
}
Call [self startConnection]; wherever you want means on viewDidLoad or on UIButton Click
You forgot to start connection. You are not saving the reference to NSURLConnection for starting the connection. So replace last line
[NSURLConnection connectionWithRequest:urlRequest delegate:self];
with this
NSURLConnection *cn =[NSURLConnection connectionWithRequest:urlRequest delegate:self];
[cn start];
Hope it helps.

Resources