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

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
+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@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Recently uploaded (20)

EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 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...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
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
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 

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];