Skip to content

Commit f02ba91

Browse files
committed
File download with three examples and runloop doesnt stop
1 parent 92eee10 commit f02ba91

File tree

3 files changed

+140
-3
lines changed

3 files changed

+140
-3
lines changed

HTTPWork.h

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
//
2+
// HTTPWork.h
3+
// Basics
4+
//
5+
// Created by sri-7348 on 28/08/18.
6+
// Copyright © 2018 sri-7348. All rights reserved.
7+
//
8+
9+
#ifndef HTTPWork_h
10+
#define HTTPWork_h
11+
12+
13+
#endif /* HTTPWork_h */

HTTPWork.m

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
//
2+
// HTTPWork.m
3+
// Basics
4+
//
5+
// Created by sri-7348 on 28/08/18.
6+
// Copyright © 2018 sri-7348. All rights reserved.
7+
//
8+
9+
#import <Foundation/Foundation.h>
10+
#import "HTTPWork.h"
11+
BOOL shouldKeepRunning=YES;
12+
@implementation HTTPWork
13+
14+
15+
-(void) uploadData{
16+
NSLog(@"hi");
17+
}
18+
19+
// needs runloop/async dispatch, make it exit runloop
20+
// dont use root user!- wont work cos file path changes
21+
-(void) downloadData{
22+
NSString *str=@"https://upload.wikimedia.org/wikipedia/en/6/62/MacOS_Mojave_Desktop.jpg";
23+
NSURL *imageURL=[NSURL URLWithString:str];
24+
NSMutableURLRequest *dRequest=[NSMutableURLRequest requestWithURL:imageURL];
25+
[dRequest setHTTPMethod:@"GET"];
26+
NSURLSession *session=[NSURLSession sharedSession];
27+
NSURLSessionDownloadTask *download=[session downloadTaskWithRequest:dRequest completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
28+
29+
if(error){
30+
NSLog(@"Error in download \n");
31+
return;
32+
}
33+
NSFileManager *fileManager = [NSFileManager defaultManager];
34+
NSURL *documentsURL = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask][0];
35+
NSURL *fileURL = [documentsURL URLByAppendingPathComponent:@"Img1.jpg"];
36+
NSError *moveError;
37+
if (![fileManager moveItemAtURL:location toURL:fileURL error:&moveError]) {
38+
NSLog(@"moveItemAtURL failed: %@", moveError);
39+
return;
40+
}
41+
NSLog(@"Response is %@: \n",response);
42+
43+
}];
44+
45+
[download resume]; //triggers the download task
46+
[[NSRunLoop currentRunLoop]run];
47+
NSLog(@"object is: %@ \n",download.progress);
48+
}
49+
50+
-(void)saveFilesInLocalDirectory //working but dont use this synchronous methos for network based URL cos takes a lot of time
51+
{
52+
NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
53+
NSString *fileName = @"gandhi.pdf";
54+
NSString *fileURL = @"http://www.mkgandhi.org/ebks/mindofmahatmagandhi.pdf";
55+
NSFileManager *fileManager = [NSFileManager defaultManager];
56+
NSString *writablePath = [documentsDirectoryPath stringByAppendingPathComponent:fileName];
57+
if(![fileManager fileExistsAtPath:writablePath]){
58+
// file doesn't exist
59+
NSLog(@"file doesn't exist");
60+
//save Image From URL
61+
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString: fileURL]];
62+
63+
NSError *error = nil;
64+
[data writeToFile:[documentsDirectoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", fileName]] options:NSAtomicWrite error:&error];
65+
66+
if (error) {
67+
NSLog(@"Error Writing File : %@",error);
68+
}else{
69+
NSLog(@"Image %@ Saved SuccessFully",fileName);
70+
}
71+
}
72+
else{
73+
// file exist
74+
NSLog(@"file exist");
75+
}
76+
}
77+
78+
// this method uses DataTask: use runloop/dispatch_async to make this work!
79+
// this doesnt exit run loop, TO.DO: make it exit once download over.
80+
// doesnt work for root user due to file paths
81+
-(void) saveFilesFast{
82+
NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
83+
NSString *str=@"http://upload.wikimedia.org/wikipedia/en/6/62/MacOS_Mojave_Desktop.jpg";
84+
NSURL *fileURL=[NSURL URLWithString:str];
85+
NSString *fileName = @"image2.jpg";
86+
NSFileManager *fileManager = [NSFileManager defaultManager];
87+
NSString *writablePath = [documentsDirectoryPath stringByAppendingPathComponent:fileName];
88+
NSURLSession *session=[NSURLSession sharedSession];
89+
NSURLSessionDataTask *task1=[session dataTaskWithURL:fileURL completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error){
90+
if(error){ //handle error
91+
NSLog(@"Error occured ! \n");
92+
NSLog(@"URL response is %@ \n",response);
93+
return;
94+
}
95+
[data writeToFile:[documentsDirectoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", fileName]] options:NSAtomicWrite error:&error];
96+
if(![fileManager fileExistsAtPath:writablePath]){
97+
NSLog(@"file doesn't exist");
98+
if (error) {
99+
NSLog(@"Error Writing File : %@",error);
100+
}
101+
102+
NSLog(@"Image %@ Saved SuccessFully",fileName);
103+
shouldKeepRunning=NO;
104+
105+
}
106+
else{
107+
NSLog(@"File exist.\n");
108+
shouldKeepRunning=NO;
109+
}
110+
}];
111+
[task1 resume];
112+
while(shouldKeepRunning){
113+
[[NSRunLoop currentRunLoop]run];
114+
}
115+
}
116+
@end

main.m

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
#import "DelegatingClass.h"
44
#import <SystemConfiguration/SystemConfiguration.h>
55
#import <Cocoa/Cocoa.h>
6-
6+
#import "HTTPWork.h"
77

88
@interface EgClass: DelegatingClass
99
- (void) threadMethod: (int) a;
@@ -220,7 +220,7 @@ int main(int argv, const char* argc[]){
220220
NSLog(@"Choice 2: Execute command line commands from a process");
221221
NSLog(@"Choice 3: Execute launchd from this program \n");
222222
//scanf("%i",&choice);
223-
choice=5;
223+
choice=7;
224224
DelegatingClass *boss =[[DelegatingClass alloc]init];
225225
EgClass *delegatePerson=[[EgClass alloc]init];
226226
boss.delegate=delegatePerson; //makes egClass conform to Delegate protocol
@@ -291,6 +291,14 @@ int main(int argv, const char* argc[]){
291291
NSLog(@"Success! \n");
292292
}
293293
}
294-
294+
else if(choice==7){
295+
//http upload and download
296+
HTTPWork *httpTask=[[HTTPWork alloc]init];
297+
//Download
298+
[httpTask downloadData];//SessionDownloadTask example
299+
[httpTask saveFilesInLocalDirectory]; //NSData with URL example
300+
[httpTask saveFilesFast];// SessionDataTask example
301+
NSLog(@"back to main \n");
302+
}
295303
return 0;
296304
}

0 commit comments

Comments
 (0)