SlideShare a Scribd company logo
1 of 19
Download to read offline
AFNetworking
Tutor : Michael
AFNetworking
• https://github.com/AFNetworking/AFNetworking
Installation
ARC Issue
Points
• Upload File
• Download File
Server
• GET Download File
• POST Upload File
• Reference http://goo.gl/OGevb
Server - Receive Data by POST
var express = require('express');
var app = express( );
app.configure(function() {
        app.use(express.bodyParser({uploadDir: './'}));
});
app.listen(8800);
var fs = require('fs');
app.post('/fileUpload', function(req, res) {
    var uploadedFile = req.files.uploadingFile;
    var tmpPath = uploadedFile.path;
    var targetPath = './' + uploadedFile.name;
    fs.rename(tmpPath, targetPath, function(err) {
        if (err) throw err;
        fs.unlink(tmpPath, function() {
                  
            console.log('File Uploaded to ' + targetPath + ' - ' + uploadedFile.size + ' bytes');
        });
    });
    res.send('file upload is done.');
    res.end();
});
<form enctype="multipart/form-data" action="upload.php"
method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadingfile" type="file" /
><br />
<input type="submit" value="Upload File" />
</form>
Server - req.files
{ uploadingFile:
   { size: 15198,
     path: '7fedaa5a4b44a499e2cfd29fc7c3be71',
     name: 'object.png',
     type: 'image/png',
     hash: false,
     lastModifiedDate: Mon Aug 27 2012 09:06:45 GMT+0800 (CST),
     _writeStream:
      { path: '7fedaa5a4b44a499e2cfd29fc7c3be71',
        fd: 10,
        writable: false,
        flags: 'w',
        encoding: 'binary',
        mode: 438,
        bytesWritten: 15198,
        busy: false,
        _queue: [],
        _open: [Function],
        drainable: true },
     length: [Getter],
     filename: [Getter],
     mime: [Getter]
    }
}
Upload Image - Http Client
NSURL *url = [NSURL URLWithString:@"http://192.168.2.104/~chronoer/
php_test/Upload.php"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
Upload Image - Data & Request
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"me.jpg"],
0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST"
path:@"" parameters:nil constructingBodyWithBlock: ^(id
<AFMultipartFormData>formData) {
[formData appendPartWithFileData:imageData name:@"uploadedfile"
fileName:@"yen.jpg" mimeType:@"image/jpeg"];
}];
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
HTML
Upload Image - Success & Fail
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
initWithRequest:request] ;
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id
responseObject) {
NSLog(@"ok");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"failed");
}];
[operation start];
Upload Image - Progress
[operation setUploadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten,
long long totalBytesExpectedToWrite) {
NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
progressView.progress = totalBytesWritten/[imageData length];
}];
Demo
FileDownload&Upload/
AFNetworkDemo
Server - Send Data by GET
app.get('/data', function(req,res) {
" if (req.query.fileName) {
" "
" " var filename = req.query.fileName;
" console.log(filename);
" "
" " fs.stat(filename, function(error, stat) {
" " if (error) { throw error; }
" " res.writeHead(200, {
" " 'Content-Type' : 'image/png',
" " 'Content-Length' : stat.size
" " });
" " });
" var fileStream = fs.createReadStream(filename);
" fileStream.on('data', function (data) {
" res.write(data);
" });
" fileStream.on('end', function() {
" res.end();
" });
" "
" }else{
" " res.writeHead(404,{"Content-Type": "application/zip"});
" " res.write("error");
" " res.end();
" }
});
Download File - Set up get link
NSURL *url = [NSURL URLWithString:[FILESERVER2 stringByAppendingFormat:@"/%@?
fileName=%@",@"data", @"yen.jpg"] ];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
initWithRequest:request];
#define FILESERVER2 @"http://localhost:8800"
// http://<server.ip>/data?fileName=yen.jpg
Download File - store file path
NSString *path = @"/Users/chronoer/Desktop/tmp/yen.jpg";
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id
responseObject) {
NSLog(@"Successfully downloaded file to %@", path);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
Download File - bind with progress view
[operation setDownloadProgressBlock:^(NSUInteger bytesWritten, long long
totalBytesRead, long long totalBytesExpectedToRead) {
long long percentDone = (totalBytesRead / totalBytesExpectedToRead);
downProgressView.progress = percentDone;
NSLog(@"Sent %lld of %lld bytes, %@", totalBytesWritten,
totalBytesExpectedToRead, path);
}];
[operation start];
Demo
• FileDownloadUpload
Question ?

More Related Content

Viewers also liked

Gregor Patorski: Mitarbeiter zu Ko-Autoren im Firmenblog machen
Gregor Patorski: Mitarbeiter zu Ko-Autoren im Firmenblog machenGregor Patorski: Mitarbeiter zu Ko-Autoren im Firmenblog machen
Gregor Patorski: Mitarbeiter zu Ko-Autoren im Firmenblog machen
ONE Schweiz
 
Experience in Europe: Dutch Exchange
Experience in Europe: Dutch ExchangeExperience in Europe: Dutch Exchange
Experience in Europe: Dutch Exchange
RAQUEL GÓMEZ BRAVO
 
Convertir texto a voz
Convertir texto a vozConvertir texto a voz
Convertir texto a voz
Andres Abril
 
Portafolio de programación Joe Holguin 2c2
Portafolio de programación Joe Holguin 2c2Portafolio de programación Joe Holguin 2c2
Portafolio de programación Joe Holguin 2c2
Joe Holguin
 
Multimedios e hipermedios para fortalecer el aprendizaje colaborativo
Multimedios e hipermedios para fortalecer el aprendizaje colaborativoMultimedios e hipermedios para fortalecer el aprendizaje colaborativo
Multimedios e hipermedios para fortalecer el aprendizaje colaborativo
Guadalupe de la Cruz
 

Viewers also liked (16)

Gregor Patorski: Mitarbeiter zu Ko-Autoren im Firmenblog machen
Gregor Patorski: Mitarbeiter zu Ko-Autoren im Firmenblog machenGregor Patorski: Mitarbeiter zu Ko-Autoren im Firmenblog machen
Gregor Patorski: Mitarbeiter zu Ko-Autoren im Firmenblog machen
 
Venta de Bmw & ktm
Venta de Bmw & ktmVenta de Bmw & ktm
Venta de Bmw & ktm
 
El espacio fisico habla
El espacio fisico hablaEl espacio fisico habla
El espacio fisico habla
 
Nadia Epm
Nadia EpmNadia Epm
Nadia Epm
 
A Framework for EU Crowdfunding
A Framework for EU CrowdfundingA Framework for EU Crowdfunding
A Framework for EU Crowdfunding
 
Arenera moreira reinalda.r
Arenera moreira reinalda.rArenera moreira reinalda.r
Arenera moreira reinalda.r
 
Logística Sostenible
Logística SostenibleLogística Sostenible
Logística Sostenible
 
Experience in Europe: Dutch Exchange
Experience in Europe: Dutch ExchangeExperience in Europe: Dutch Exchange
Experience in Europe: Dutch Exchange
 
Steps to enroll DSME
Steps to enroll DSMESteps to enroll DSME
Steps to enroll DSME
 
Convertir texto a voz
Convertir texto a vozConvertir texto a voz
Convertir texto a voz
 
Portafolio de programación Joe Holguin 2c2
Portafolio de programación Joe Holguin 2c2Portafolio de programación Joe Holguin 2c2
Portafolio de programación Joe Holguin 2c2
 
community manager
community managercommunity manager
community manager
 
Multimedios e hipermedios para fortalecer el aprendizaje colaborativo
Multimedios e hipermedios para fortalecer el aprendizaje colaborativoMultimedios e hipermedios para fortalecer el aprendizaje colaborativo
Multimedios e hipermedios para fortalecer el aprendizaje colaborativo
 
Screen Australia Info Guide
Screen Australia Info GuideScreen Australia Info Guide
Screen Australia Info Guide
 
22 Curso Intensivo - Estrategias en Marketing Digital
22 Curso Intensivo - Estrategias en Marketing Digital22 Curso Intensivo - Estrategias en Marketing Digital
22 Curso Intensivo - Estrategias en Marketing Digital
 
Estatuto Trabajadores
Estatuto TrabajadoresEstatuto Trabajadores
Estatuto Trabajadores
 

More from Michael Pan

Google maps SDK for iOS 1.4
Google maps SDK for iOS 1.4Google maps SDK for iOS 1.4
Google maps SDK for iOS 1.4
Michael Pan
 
Autorelease pool
Autorelease poolAutorelease pool
Autorelease pool
Michael Pan
 
Objc under the_hood_2013
Objc under the_hood_2013Objc under the_hood_2013
Objc under the_hood_2013
Michael Pan
 
比價撿便宜 Steven
比價撿便宜 Steven比價撿便宜 Steven
比價撿便宜 Steven
Michael Pan
 
Appsgaga - iOS Game Developer
Appsgaga - iOS Game DeveloperAppsgaga - iOS Game Developer
Appsgaga - iOS Game Developer
Michael Pan
 
GZFox Inc. Jacky
GZFox Inc. JackyGZFox Inc. Jacky
GZFox Inc. Jacky
Michael Pan
 
創投公司 hoku_20121017
創投公司 hoku_20121017創投公司 hoku_20121017
創投公司 hoku_20121017
Michael Pan
 

More from Michael Pan (20)

Activity
ActivityActivity
Activity
 
Shootting Game
Shootting GameShootting Game
Shootting Game
 
Introduction to Android Studio
Introduction to Android StudioIntroduction to Android Studio
Introduction to Android Studio
 
Eclipse and Genymotion
Eclipse and GenymotionEclipse and Genymotion
Eclipse and Genymotion
 
Note something
Note somethingNote something
Note something
 
Strategy Pattern for Objective-C
Strategy Pattern for Objective-CStrategy Pattern for Objective-C
Strategy Pattern for Objective-C
 
Core data lightweight_migration
Core data lightweight_migrationCore data lightweight_migration
Core data lightweight_migration
 
Google maps SDK for iOS 1.4
Google maps SDK for iOS 1.4Google maps SDK for iOS 1.4
Google maps SDK for iOS 1.4
 
Homework2 play cards
Homework2 play cardsHomework2 play cards
Homework2 play cards
 
Autorelease pool
Autorelease poolAutorelease pool
Autorelease pool
 
Objc under the_hood_2013
Objc under the_hood_2013Objc under the_hood_2013
Objc under the_hood_2013
 
Prototype by Xcode
Prototype by XcodePrototype by Xcode
Prototype by Xcode
 
Dropbox sync
Dropbox syncDropbox sync
Dropbox sync
 
Nimbus
NimbusNimbus
Nimbus
 
Superstar dj pdf
Superstar dj pdfSuperstar dj pdf
Superstar dj pdf
 
ADB - Arthur
ADB - ArthurADB - Arthur
ADB - Arthur
 
比價撿便宜 Steven
比價撿便宜 Steven比價撿便宜 Steven
比價撿便宜 Steven
 
Appsgaga - iOS Game Developer
Appsgaga - iOS Game DeveloperAppsgaga - iOS Game Developer
Appsgaga - iOS Game Developer
 
GZFox Inc. Jacky
GZFox Inc. JackyGZFox Inc. Jacky
GZFox Inc. Jacky
 
創投公司 hoku_20121017
創投公司 hoku_20121017創投公司 hoku_20121017
創投公司 hoku_20121017
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

Afnetworking 26.key

  • 6. Server • GET Download File • POST Upload File • Reference http://goo.gl/OGevb
  • 7. Server - Receive Data by POST var express = require('express'); var app = express( ); app.configure(function() {         app.use(express.bodyParser({uploadDir: './'})); }); app.listen(8800); var fs = require('fs'); app.post('/fileUpload', function(req, res) {     var uploadedFile = req.files.uploadingFile;     var tmpPath = uploadedFile.path;     var targetPath = './' + uploadedFile.name;     fs.rename(tmpPath, targetPath, function(err) {         if (err) throw err;         fs.unlink(tmpPath, function() {                                console.log('File Uploaded to ' + targetPath + ' - ' + uploadedFile.size + ' bytes');         });     });     res.send('file upload is done.');     res.end(); }); <form enctype="multipart/form-data" action="upload.php" method="POST"> <input type="hidden" name="MAX_FILE_SIZE" value="100000" /> Choose a file to upload: <input name="uploadingfile" type="file" / ><br /> <input type="submit" value="Upload File" /> </form>
  • 8. Server - req.files { uploadingFile:    { size: 15198,      path: '7fedaa5a4b44a499e2cfd29fc7c3be71',      name: 'object.png',      type: 'image/png',      hash: false,      lastModifiedDate: Mon Aug 27 2012 09:06:45 GMT+0800 (CST),      _writeStream:       { path: '7fedaa5a4b44a499e2cfd29fc7c3be71',         fd: 10,         writable: false,         flags: 'w',         encoding: 'binary',         mode: 438,         bytesWritten: 15198,         busy: false,         _queue: [],         _open: [Function],         drainable: true },      length: [Getter],      filename: [Getter],      mime: [Getter]     } }
  • 9. Upload Image - Http Client NSURL *url = [NSURL URLWithString:@"http://192.168.2.104/~chronoer/ php_test/Upload.php"]; AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
  • 10. Upload Image - Data & Request NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"me.jpg"], 0.5); NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) { [formData appendPartWithFileData:imageData name:@"uploadedfile" fileName:@"yen.jpg" mimeType:@"image/jpeg"]; }]; <form enctype="multipart/form-data" action="upload.php" method="POST"> <input type="hidden" name="MAX_FILE_SIZE" value="100000" /> Choose a file to upload: <input name="uploadedfile" type="file" /><br /> <input type="submit" value="Upload File" /> </form> HTML
  • 11. Upload Image - Success & Fail AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request] ; [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"ok"); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"failed"); }]; [operation start];
  • 12. Upload Image - Progress [operation setUploadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) { NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite); progressView.progress = totalBytesWritten/[imageData length]; }];
  • 14. Server - Send Data by GET app.get('/data', function(req,res) { " if (req.query.fileName) { " " " " var filename = req.query.fileName; " console.log(filename); " " " " fs.stat(filename, function(error, stat) { " " if (error) { throw error; } " " res.writeHead(200, { " " 'Content-Type' : 'image/png', " " 'Content-Length' : stat.size " " }); " " }); " var fileStream = fs.createReadStream(filename); " fileStream.on('data', function (data) { " res.write(data); " }); " fileStream.on('end', function() { " res.end(); " }); " " " }else{ " " res.writeHead(404,{"Content-Type": "application/zip"}); " " res.write("error"); " " res.end(); " } });
  • 15. Download File - Set up get link NSURL *url = [NSURL URLWithString:[FILESERVER2 stringByAppendingFormat:@"/%@? fileName=%@",@"data", @"yen.jpg"] ]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; #define FILESERVER2 @"http://localhost:8800" // http://<server.ip>/data?fileName=yen.jpg
  • 16. Download File - store file path NSString *path = @"/Users/chronoer/Desktop/tmp/yen.jpg"; operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO]; [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"Successfully downloaded file to %@", path); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error: %@", error); }];
  • 17. Download File - bind with progress view [operation setDownloadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesRead, long long totalBytesExpectedToRead) { long long percentDone = (totalBytesRead / totalBytesExpectedToRead); downProgressView.progress = percentDone; NSLog(@"Sent %lld of %lld bytes, %@", totalBytesWritten, totalBytesExpectedToRead, path); }]; [operation start];