zoukankan      html  css  js  c++  java
  • iOS- 利用AFNetworking(AFN)

    iOS- 利用AFNetworking(AFN) - 实现图片上传 

     官方建议AFN的使用方法

     1. 定义一个全局的AFHttpClient:包含有

        1> baseURL

        2> 请求

        3> 操作队列 NSOperationQueue

     2. 由AFHTTPRequestOperation(HTTP请求操作)负责所有的网络操作请求

     3. 修改xxx-Prefix.pch文件

    #import <MobileCoreServices/MobileCoreServices.h>

    #import <SystemConfiguration/SystemConfiguration.h>

    0.导入框架准备工作

    •1. 将框架程序拖拽进项目

    •2.  添加iOS框架引用

    –SystemConfiguration.framework

    –MobileCoreServices.framework

    •3.  引入

    #import "AFNetworking.h"

    1.AFN的客户端,使用基本地址初始化,同时会实例化一个操作队列,以便于后续的多线程处理

     

    2.利用AFN实现文件上传操作细 1 #pragma mark - 文件上传

     2 - (IBAction)uploadImage
     3 {
     4     /*
     5      此段代码如果需要修改,可以调整的位置
     6      
     7      1. 把upload.php改成网站开发人员告知的地址
     8      2. 把file改成网站开发人员告知的字段名
     9      */
    10     // 1. httpClient -> url
    11     // AFN的客户端,使用基本地址初始化,同时会实例化一个操作队列,以便于后续的多线程处理
    5     NSURL *url = [NSURL URLWithString:@"http://192.168.3.255/~apple/qingche"];
    6     AFHTTPClient *_httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
      NSOperationQueue *_queue = [[NSOperationQueue alloc] init];
    12 // 2. 上传请求POST 13 NSURLRequest *request = [_httpClient multipartFormRequestWithMethod:@"POST" path:@"upload.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 14 // 在此位置生成一个要上传的数据体,form对应的是html文件中的表单 18 UIImage *image = [UIImage imageNamed:@"头像1"]; 19 NSData *data = UIImagePNGRepresentation(image); 21 // 在网络开发中,上传文件时,是文件不允许被覆盖,文件重名,要解决此问题, 可以在上传时使用当前的系统事件作为文件名 24 NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 25 // 设置时间格式 26 formatter.dateFormat = @"yyyyMMddHHmmss"; 27 NSString *str = [formatter stringFromDate:[NSDate date]]; 28 NSString *fileName = [NSString stringWithFormat:@"%@.png", str]; 31 /* 32 此方法参数 33 1. 要上传的[二进制数据] 34 2. 对应网站上[upload.php中]处理文件的[字段"file"] 35 3. 要保存在服务器上的[文件名] 36 4. 上传文件的[mimeType] 37 */ 
    [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"]; 39 }]; 41 // 3. operation(HTTP请求操作)包装的urlconnetion 42 AFHTTPRequestOperation *httpROpe = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 44 [httpROpe setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 45 NSLog(@"上传完成"); 46 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 47 NSLog(@"上传失败->%@", error); 48 }]; 50 //执行 51 [_httpClient.operationQueue addOperation:op];
     
  • 相关阅读:
    Phalanx--hdu2859(dp 最大对称子图)
    Spring Cloud-hystrix Dashboard(八)
    Spring Cloud-hystrix使用例子(七)
    mysql deadlock、Lock wait timeout解决和分析
    Spring Cloud-hystrix(六)
    Spring Cloud-Ribbon负载均衡策略类IRule(五)
    Spring Cloud-Ribbon ILoadBalancer负载均衡器核心源码(四)
    Spring Cloud-Ribbon实现客户端的服务均衡(三)
    Spring Cloud-Eureka实现服务的注册与发现(二)
    Spring Cloud-个人理解的微服务演变过程(一)
  • 原文地址:https://www.cnblogs.com/iOS-mt/p/4246496.html
Copyright © 2011-2022 走看看