Pause and Resume downloads in Objective-C - objective-c

Everything seems to work well except the pause/resume functionality. My issue is that when a download tries to continue from where it left off,set the header range but not work properly. When I download zip file and extract it,extracted file extension is download.zip.cpgz. Please fix my issue.
My code:
**UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectZero];
NSString* secretAgent = [webView stringByEvaluatingJavaScriptFromString:#"navigator.userAgent"];
NSLog(#"user aggent %#",secretAgent);
if([[NSFileManager defaultManager] fileExistsAtPath:_path]){
NSDictionary *fileDictionary = [[NSFileManager defaultManager] fileAttributesAtPath:_path traverseLink:YES];
unsigned long long int h = [fileDictionary fileSize];
_textField.text = self.textField.text;
//[self performSelectorInBackground:#selector(downloadZipfile) withObject:nil];
// NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:_textField.text]
//
// cachePolicy:NSURLRequestUseProtocolCachePolicy
//
// timeoutInterval:60.0];
//NSFileSize *fileSize = [NSFileSize]
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.textField.text]];
NSString *range = #"bytes=";
range = [range stringByAppendingString:[[NSNumber numberWithInt:h] stringValue]];
range = [range stringByAppendingString:#"-"];
[request setHTTPMethod:#"GET"];
[request setValue:#"keep-live" forHTTPHeaderField:#"Connection"];
[request setValue:range forHTTPHeaderField:#"Keep-Alive"];
[request setValue:secretAgent forHTTPHeaderField:#"User-Agent"];
[request setValue:range forHTTPHeaderField:#"Range"];
NSLog(#"range set %#",range);
// create the connection with the request
// and start loading the data
_downloadConeection=[[NSURLConnection alloc] initWithRequest:request delegate:self];**

Related

Parse xml(from web service) to NSDictionary in objective c

I do synchronous post request and get xml. Now I need parse and save it in NSDictionary. I tried many solutions from the web. But nothing worked for me. Here's my code:
//Response data object
NSData *returnData = [[NSData alloc]init];
NSString *param = #"{params}";
NSString *postString = [NSString stringWithFormat:#"request=%#",param];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"url"]];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[postString length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
//Send the Request
returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
//Get the Result of Request
NSString *response = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];
bool debug = YES;
NSDictionary *xmlDoc = [NSDictionary dictionaryWithXMLFile:response];
if (debug && response) {
NSLog(#"Response >>>> %#", xmlDoc);
}
I used this xml reader. Here is result which I get in nslog:
2016-11-28 18:04:26.970 SyncPostReq[8667:305923] Response >>>> (null)
NSURL *url = [NSURL URLWithString:#"url"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:url
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
NSError *parseError;
NSDictionary* xmlDict1 = [XMLReader dictionaryForXMLData:data error:&parseError];
NSDictionary *dictData = [xmlDict1 objectForKey:#"event_listing"];
arrData = [dictData objectForKey:#"event"];
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[defaults setObject:arrData
forKey:#"Keyupevent"];
[defaults setBool:YES forKey:#"KeyalldataLoad"];
[defaults synchronize];
uparrData =[[defaults objectForKey:#"Keyupevent"] mutableCopy];
[arrStoreAllEventsData addObjectsFromArray:uparrData];
[self.tblView reloadData];
[self loadPastEventdatafromxml];
}] resume];

Objective-C Asynchronous NSURLConnection to Ruby Server

I am having trouble sending asynchronous NSURLRequests to a Ruby server. When I use the following, a connection is never made:
self.data = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://domain.com/app/create_account.json"]];
[request setHTTPMethod:#"POST"];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request addValue:#"form-data" forHTTPHeaderField:#"Content-Disposition"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
However, when I exchange the last line with:
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
Everything works great. But I do need to make this connection asynchronously...
EDIT-Working Example
NSURL *url = [NSURL URLWithString:#"http://domain.com/app/create_account.json"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:data forKey:#"data"];
[request setDelegate:self];
[request startAsynchronous];
It seems RESTful services need their own third party framework in this case.
you can try following using restkit api
- (void)sendAsJSON:(NSDictionary*)dictionary {
RKClient *client = [RKClient clientWithBaseURL:#"http://restkit.org"];
// create a JSON string from your NSDictionary
id<RKParser> parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:RKMIMETypeJSON];
NSError *error = nil;
NSString *json = [parser stringFromObject:dictionary error:&error];
// send your data
if (!error)
[[RKClient sharedClient] post:#"/some/path" params:[RKRequestSerialization serializationWithData:[json dataUsingEncoding:NSUTF8StringEncoding] MIMEType:RKMIMETypeJSON] delegate:self];
}
referance:
https://github.com/RestKit/RestKit/wiki/Tutorial-%3A-Introduction-to-RestKit
https://github.com/RestKit/RestKit/wiki/Posting-NSDictionary-as-JSON
Thanks
Nikhil

NSURLConnection freeze

I'm trying to send JSON post using NSURLConnection:
NSURL *url = [NSURL URLWithString:urlStr];
NSString *jsonPostBody = [NSString stringWithFormat:#"{\"user\":""\"%#\""",\"pass\":""\"%#\""",\"listades\":\"\"}",
[username stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[password stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"JSNON BODY:%#", jsonPostBody);
NSData *postData = [jsonPostBody dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
[request setTimeoutInterval:2.0];
NSString* postDataLengthString = [[NSString alloc] initWithFormat:#"%d", [postData length]];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:postDataLengthString forHTTPHeaderField:#"Content-Length"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
App execution gets freeze when it reaches connection command, despite timeout.
I'm stucked in this issue and I can not find a solution.
Many thanks
-(void) jsonRESTWebServiceMethod:(NSString*)method WithParameter:(NSMutableDictionary*)params{
self.iResponseType = JSONTYPE;
NSMutableDictionary *bodyDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:method,#"name",params,#"body",nil,nil];
NSData *data = [[CJSONSerializer serializer] serializeObject:bodyDict error:nil];
NSString *strRequest = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
strRequest = [NSString stringWithFormat:#"json=%#",strRequest];
NSData *body = [strRequest dataUsingEncoding:NSUTF8StringEncoding];
NSString *strURL = [NSString stringWithString:WebServiceURL];
NSString* escapedUrlString = [strURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSMutableURLRequest *request= [NSMutableURLRequest requestWithURL:[NSURL URLWithString:escapedUrlString]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:body];
NSString *msgLength = [NSString stringWithFormat:#"%d",strRequest.length];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField: #"Content-Type"];
[request addValue:msgLength forHTTPHeaderField:#"Content-Length"];
if (mydata) {
[mydata release];
mydata = nil;
}
conections = [[NSURLConnection alloc] initWithRequest:request delegate:self];
mydata = [[NSMutableData alloc] init];
}
It's freezing your app because you have passed YES into startImmediately. This will freeze the app until request is finished.
You need to use something like connectionWithRequest:delegate: - this will run the request in the background and tell you when it's done.
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];

iphone SDK: How to post data to a url?

This may be a duplicate question but i could not find my answer when searching. So, How do i post data to a url? Heres what i got so far:
NSString *url = #"https://localhost/login.php";
NSURL *urlr = [NSURL URLWithString:url];
NSMutableURLRequest *urlre = [[NSMutableURLRequest alloc] init];
[urlre setURL:[NSURL URLWithString:url]];
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
NSString *user = [defs stringForKey:#"User"];
NSString *pass = [defs stringForKey:#"Pass"];
NSInteger *version = [defs integerForKey:#"Version"];
NSString *bodyData = [[NSString alloc] initWithFormat:#"user=%#&password=%#&version=%d",user,pass,version];
NSData *body = [bodyData dataUsingEncoding:NSASCIIStringEncoding];
NSURLResponse *response = nil;
NSError *error = nil;
[urlre setHTTPMethod:#"POST"];
[urlre setValue:[[NSString alloc] initWithFormat:#"%d",[body length]] forHTTPHeaderField:#"Content-Length"];
[urlre setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlre setHTTPBody:body];
NSData *dataThis = [NSURLConnection sendSynchronousRequest:urlre returningResponse:&response error:&error];
if(dataThis)
{
NSLog(#"Connect Success");
} else {
NSLog(#"%#",[error localizedDescription]);
}
Is the above correct? In my
-(void) connection:(NSURLConnection*)connection didReceiveData:(NSData *)data
event, I get nothing. Even in the didFinishLoading it gets nothing with NSLog. Please help.
Have you set a delegate for your request?
Why don't you have a look at using a framework like ASIHTTPRequest, makes things so simple. Check it out http://allseeing-i.com/ASIHTTPRequest/

How can I deal with a file being split into several parts, when I send it to a server?

I am trying to write code in Objective C which should send a JPEG file to a server. The problem is that the file is split into several parts, and only the first part is getting there. Is there a way of dealing with this?
Here is some of the code:
int j;
for (j = 0; j < 5; j++) {
// Read in data from appropriate signature file
NSMutableString *imagePath = [folder_path_2 mutableCopy];
[imagePath appendString:fn[j]];
[imagePath appendString:#".jpeg"];
NSLog(imagePath);
NSData *imageData = nil;
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:imagePath];
if (fileExists) {
imageData = [[NSData alloc] initWithContentsOfFile:imagePath];
} else {
NSLog(#"JPEG image file does not exist.");
}
request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlStr]];
[request setHTTPMethod:#"POST"];
[request setValue:#"image/jpeg" forHTTPHeaderField:#"Accept"];
[request setValue:#"image/jpeg" forHTTPHeaderField:#"Content-Type"];
int len = (int)[imageData length];
length_str = [NSString stringWithFormat: #"%d", len];
[request setValue:length_str forHTTPHeaderField:#"Content-Length"];
postBody = [NSMutableData data];
[postBody appendData:[NSData dataWithData:imageData]];
[request setHTTPBody:postBody];
// Make connection to the Internet
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil
error:nil];
NSString *returnString = (NSString*)[[NSString alloc] initWithData:returnData
encoding:NSUTF8StringEncoding];
NSLog(returnString);
}
How big is the jpeg file that you're trying to send?