asihttprequest download file, But shutdown when screen lock - ios

I use IOS7
I start download and i lock screen, and i open screen. My program is shutdown...
Is there some can help me ?
This is major code:
init download url:
NSURL *url = [NSURL URLWithString:dictionaryUrl];
ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
set ASIHTTPRequest delegate:
request.delegate = self;
init file save path:
NSString *savePath = [path stringByAppendingPathComponent:name];
bool b=[ fileManager createFileAtPath :savePath contents : nil attributes : nil ];
if (b){
fileHandle=[ NSFileHandle fileHandleForWritingAtPath :savePath];
}
[request setAllowResumeForFileDownloads:NO];
[request setDelegate:self];
[request setDidFinishSelector:#selector(requestDone:)];
[request setDidFailSelector:#selector(requestWentWrong:)];
[request setDataReceivedBlock :^( NSData * data){
[fileHandle seekToEndOfFile ];
[fileHandle writeData :data];
[ label setText :[ NSString stringWithFormat : #"downloading...%.1f %%" , process . progress * 100 ]];
}];
[request setDownloadProgressDelegate:process];
add to ASINetworkQueue:
[self.netWorkQueue addOperation:request];
relase request:
[request release];

First, you need to enable the request to run at background. add this :
[request setShouldContinueWhenAppEntersBackground:YES];
for quick task it's possible, works like charm. but for long running task, just like you wanted, to keep continue download, you need to add a bit code, to enable this request from being terminated because run too long.
I've answered question for location update by adding timer and fire API every x seconds indefinitely. using UIBackgroundTaskIdentifier and NSTimer. This should give you an idea. should be same concept of what you are doing.
How do I get a background location update every n minutes in my iOS application?

When your screen gets lock your app goes to background.You can perform tasks for a limited time after your application is directed to go to the background, but only for the duration provided. Running for longer than this will cause your application to be terminated. See the "Completing a Long-Running Task in the Background" section of the iOS Application Programming Guide for how to go about this.
For iOS7 you can check this link https://stackoverflow.com/a/19355437/1372368.
And the code snippet to run task in background you can find various links like:How to keep an iPhone app running on background fully operational

Related

ResumeData getting nil when using downloadTaskWithRequest

If I'm using this below code
aDownloadTask = [self.backgroundSession downloadTaskWithURL:aRemoteURL];
Desc of above code:
When I started download by using downloadTaskWithURL It’s return expectedContentLength negative(-1) But that time resume data getting perfectly.
Another one is
For solved above problem I'm using this below code
NSMutableURLRequest *aURLRequest = nil;
aURLRequest = [[NSMutableURLRequest alloc] initWithURL:aRemoteURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
[aURLRequest setHTTPMethod:#"POST"];
[aURLRequest setValue:#"identity" forHTTPHeaderField:#"Accept-Encoding"];
aDownloadTask=[self.backgroundSession downloadTaskWithRequest:aURLRequest];
Desc of above code: Using above code expectedContentLength getting perfectly. But issue is the when pause downloading resume data nil every time.
Thats why my downloading start from beginning and not from that point when I pause.
Thanks in advance
Please , remove this below line from your code and try. Your resume data will getting perfectly.
[aURLRequest setHTTPMethod:#"POST"];

UIWebview white screen after application enters foreground

my application is just a simple webview which loads a given url. My problem is that if I turn on my application after some time, the webview doesn't show its content any more. My question is how to know if a webview has rendered something, or is it showing white screen and i have to reload it.
I've searched SO with no luck, so I would appreciate any suggestions or directions to sites where I could find a solution to my problem.
Thanks in advance!
In case anyone needs this I'm loading content like this and everything works, except when i don't use it for some time and it sits in the background, after it enters foreground it is white. I guess iOS is handling memory this way, and clears the webview.
- (void)loadWebView
{
NSDate *date = [NSDate date];
long unixTimeStamp = (long)[date timeIntervalSince1970];
NSString *urlString = [NSString stringWithFormat:#"http://www.myurlExample.com/mobile/?timestamp=%lu&secret=%#",unixTimeStamp,[[NSUserDefaults standardUserDefaults] objectForKey:kUniqueUserSecretID]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
[request setHTTPShouldHandleCookies:YES];
NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies: cookies];
[request setAllHTTPHeaderFields:headers];
[self.webView loadRequest:request];
}
Sounds like the problem occurs when you foreground the app?
You can do something like this in your AppDelegate.m:
- (void)applicationWillEnterForeground:(UIApplication *)application {
// Depending on the architecture of your app, grab the handler to your controller that contains the webView
[webViewController.webview reload];
}
One way might be to use -stringByEvaluatingJavaScriptFromString: to check on the web view's content. For example, you could do something like:
NSString *head =
[myWebView stringByEvaluatingJavaScriptFromString:
#"document.getElementsByTagName(\"head\")"];

Box.Net iOS SDK Moving Files and Folders

I am currently developing an iOS application and am implementing the Box.Net SDK. I have gotten everything to work except the ability to move files around, which is not a native feature of the SDK. I am trying to twist my way through it.
If you are familiar with the structure of Box.Net, each file/folder has an ID number for itself, and an ID its parent. From what I understand if I want to move a file, I am supposed to change the parent ID number on the file which will point it to the new location. I can't seem to get it to work properly though. My application seems to keep crashing.
This is what I have so far, generalized.
BoxObject *boxObject = [[[Box objectWithID:(ID#ofParent)] children] objectAtIndex:i];
[boxObject parent].boxID = 0; // <-- Problem (causes crash)
I also tried this.
[boxObject setParent:[Box folderWithID:[BoxID numberWithInt:i]]];
The boxObject variable is the file that I want to move. I am setting its parent ID equal to 0, which is supposed to be the root folder. However, my application crashes when I try to reassign the parent ID for the file. Any ideas on how to successfully move files/folders? Any help is much appreciated! Thanks in advance!
Okay. I suppose there wasn't a way to do fix this in-house with the SDK. So, I had to send out an external PUT request. I used the following code to handle moving files.
- (void)moveItem:(BoxObject *)object toParentFolderWithID:(BoxID *)parentID
{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://api.box.com/2.0/files/%#", object.boxID]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"PUT"];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *auth = [NSString stringWithFormat:#"BoxAuth api_key=%#&auth_token=%#",[Box boxAPIKey],[defaults objectForKey:#"box-api-auth-token"]];
NSString *payload = [NSString stringWithFormat:#"{\"parent\": {\"id\": %#}}", parentID];
[request setHTTPBody:[NSMutableData dataWithData:[payload dataUsingEncoding:NSUTF8StringEncoding]]];
[request setValue:auth forHTTPHeaderField:#"Authorization"];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
[connection start];
}
Just as a reminder if you are new to the Box SDK, you will most likely need to update/refresh the data after moving the files. If not handled, your application could crash if the file doesn't exist. Hope this helps to anyone was not sure about this.

NSURL Request? Registration and Login

Here is my code:
//login method
- (int) authenticateClient {
NSString *loginWeb = [NSString stringWithFormat:(#"http://192.168.118.1/login.php?uname=%#&pass=%#&submit=Log%%20In"), user, pass];
NSURL *login = [NSURL URLWithString:loginWeb];
NSData *loginData = [NSData dataWithContentsOfURL: login];
NSString *result = [[NSString alloc] initWithData:loginData encoding:NSUTF8StringEncoding];
NSMutableURLRequest *loginRequest = [[NSMutableURLRequest alloc] init];
[loginRequest setURL:login];
[loginRequest setTimeoutInterval:1];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:loginRequest delegate:self startImmediately:YES];
[connection start];
return [result integerValue];
}
My question is, when simulating having no network connection, my app freezes up and doesn't load or time out in the specified interval (1 second just to see if it works).
I read something about start immediately forces in to run on the current threat causing everything else to "pause" until the action is complete.
I have two questions:
1.) What is a better method to have the URL basically run in the background instead of pausing everything?
2.) How can I get a timeout method that actually works?
Much appreciation! Thanks!
Well, one second as timeout is really low. If you want to simulate different network conditions, you can use something like this. You don't need to this dance:
NSData *loginData = [NSData dataWithContentsOfURL: login];
NSString *result = [[NSString alloc] initWithData:loginData encoding:NSUTF8StringEncoding];
You don't need this as well, since the connection has started already:
[connection start];
Also from the documentation:
NSURLConnection’s delegate methods—defined by the
NSURLConnectionDelegate Protocol protocol—allow an object to receive
informational callbacks about the asynchronous load of a URL request.
Other delegate methods provide facilities that allow the delegate to
customize the process of performing an asynchronous URL load. These
delegate methods are called on the thread that started the
asynchronous load operation for the associated NSURLConnection object.
So for your questions:
Implement the NSURLConnection’s delegate
Check this & this.

Corrupted image when uploading in background

I'm developping a little image sharing app for my company. Everything works pretty fine except for one thing : when I upload an image to the server, and switch the app to background, a part of the image is corrupted (all gray).
It seems that the image data is sent correctly as long as the app is live. As soon as I switch to background, it sends nothing as it seems.
For the record, I use ASIHttpRequest, the shouldContinueWhenAppEntersBackground is set to YES and I'm running the app from iOS 4.3 to iOS 6.0. I'm using ARC.
I tried to "retain" (through a strong reference) both the image and the data, nothing there too.
Here are parts of the code :
The
Webservice that sends the image
- (void)sendImage:(UIImage*)image forEmail:(NSString*)email
{
NSString* uploadImage = [NSString stringWithFormat:[self completeUrlForService:SEND_PHOTO], email];
NSURL* url = [NSURL URLWithString:[uploadImage stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"uploadImage %#", uploadImage);
// setting that we will send a JSON object
[self setRequestType:WebServiceWrapperTypePOSTRequest];
// when posting a picture, it could take more time...
self.request.timeOutSeconds = 4*60;
[self.request setShouldContinueWhenAppEntersBackground:YES];
// setting up the POST data
[self addPostData:image forKey:#"fileContents"];
// start the request
[self startRequestForUrl:url userInfo:[NSDictionary dictionaryWithObject:SEND_PHOTO forKey:URL_KEY]];
}
the actual part of ASIHttpRequest class
self.request = [ASIHTTPRequest requestWithURL:url];
[self.request setShouldContinueWhenAppEntersBackground:YES];
NSString* key = [[self.postDictionnary allKeys] objectAtIndex:0];
UIImage* value = [self.postDictionnary valueForKey:key];
__strong NSData* data = UIImageJPEGRepresentation(value, 1.0);
if (!data) data = UIImagePNGRepresentation(value);
[self.request appendPostData:data];
[self.request setPostLength:data.length];
[self.request setUserInfo:userInfo];
[self.request setDelegate:self];
[self.request startAsynchronous];
If any of you guys has the tinyest idea, I'll take it!
Thanks.
Finally I decided to use a different library (MKNetworkKit) and instead of sending an UIImage, I save the image on disk to the tmp folder and send the file instead. When the download is complete, I just delete the image on disk. It worked liked a charm :)

Resources