afnetworking 26.key

19
AFNetworking Tutor : Michael

Upload: michael-pan

Post on 15-May-2015

1.090 views

Category:

Technology


1 download

DESCRIPTION

http://www.facebook.com/pages/Developers-note/226724001803

TRANSCRIPT

Page 1: Afnetworking 26.key

AFNetworkingTutor : Michael

Page 2: Afnetworking 26.key

AFNetworking• https://github.com/AFNetworking/AFNetworking

Page 3: Afnetworking 26.key

Installation

Page 4: Afnetworking 26.key

ARC Issue

Page 5: Afnetworking 26.key

Points• Upload File

• Download File

Page 6: Afnetworking 26.key

Server• GET Download File

• POST Upload File

• Reference http://goo.gl/OGevb

Page 7: Afnetworking 26.key

Server - Receive Data by POSTvar 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>

Page 8: Afnetworking 26.key

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

Page 9: Afnetworking 26.key

Upload Image - Http ClientNSURL *url = [NSURL URLWithString:@"http://192.168.2.104/~chronoer/php_test/Upload.php"];

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];

Page 10: Afnetworking 26.key

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

Page 11: Afnetworking 26.key

Upload Image - Success & FailAFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request] ;

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"ok"); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"failed"); }];

[operation start];

Page 12: Afnetworking 26.key

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

Page 13: Afnetworking 26.key

DemoFileDownload&Upload/AFNetworkDemo

Page 14: Afnetworking 26.key

Server - Send Data by GETapp.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();" }});

Page 15: Afnetworking 26.key

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

Page 16: Afnetworking 26.key

Download File - store file pathNSString *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);}];

Page 17: Afnetworking 26.key

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

Page 18: Afnetworking 26.key

Demo

• FileDownloadUpload

Page 19: Afnetworking 26.key

Question ?