如何在 Xcode 8 和 iOS 10 中使用 AFNetworking 类和 Swift 3 上传图像

Posted

技术标签:

【中文标题】如何在 Xcode 8 和 iOS 10 中使用 AFNetworking 类和 Swift 3 上传图像【英文标题】:How do I upload an image using AFNetworking class with Swift 3 in Xcode 8 and iOS 10 【发布时间】:2017-04-28 04:45:36 【问题描述】:
manager.post(urlString, parameters: perameter, progress: nil,
                     success:
                        
                            requestOperation, response in
                            SVProgressHUD.dismiss()

                            let json = try! JSONSerialization.jsonObject(with: (response as! NSData) as Data, options:.allowFragments) as! NSDictionary
                            self.listData = json["Result"] as! [NSDictionary]
                            print(self.listData)
                            self.tableViewOutlet.reloadData()




                        ,
                        failure:
                        
                            requestOperation, error in
                            print(error.localizedDescription)
                        )

【问题讨论】:

你用过 alamofire 吗? 你能看懂目标代码吗? 我只使用 AFNetworking 只有 Swift 3 代码我想通过 post 请求上传图片 试过this? 【参考方案1】:

对于图片上传,您可以使用多部分。

manager.responseSerializer.acceptableContentTypes = ["text/html"]
    manager.post(url as String, parameters: dic, constructingBodyWith:  (data) in
                if imgData != nil
                
                    data.appendPart(withFileData: imgData!, name: "image", fileName: imgName as String , mimeType: "image/jpeg")

                
            , progress: nil, success:  (sessiondata, result) in
                UIApplication.shared.isNetworkActivityIndicatorVisible = true


                let dict = result as! Dictionary<String, AnyObject>
                print(dict)
                if (dict["status"]?.boolValue == true)
                
                    block(dict as NSDictionary?)
                
                else
                    block(dict as NSDictionary?)
                
            )  (data, result) -> Void in
                let errorDict = ["error": data?.error?.localizedDescription as AnyObject]

                UIApplication.shared.isNetworkActivityIndicatorVisible = false
                block(errorDict as NSDictionary?)

            

【讨论】:

【参考方案2】:

试试这个:

let manager = AFHTTPRequestOperationManager()
            let url = "http://path/to/server"
            let URL : NSURL = NSURL(string: url)!
            let req : NSURLRequest = NSURLRequest(URL: URL)
    let fileURL = NSURL(string: "file:///var/mobile/Media/DCIM/102APPLE/IMG_2623.PNG")// change your image url
            manager.POST( url, parameters: nil,
                constructingBodyWithBlock:  (data: AFMultipartFormData!) in
                    do
                        _ = try data.appendPartWithFileURL(fileURL!, name: "uploaded_file", fileName: "image.png", mimeType: "image/png")
                    catch
                    
                ,
                success:  (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
                    print("\(responseObject)")
                ,
                failure:  (operation: AFHTTPRequestOperation!, error: NSError!) in
                    print("\(error.localizedDescription)")
            )

【讨论】:

您可以根据需要上传图像或图像数据,您可以在此更改 _ = try data.appendPartWithFileURL(fileURL!, name: "uploaded_file", fileName: "image.png", mimeType : "图片/png") 让 imageData = UIImageJPEGRepresentation(yourimage, 0.5) formData.appendPartWithFileData(imageData!, name: "Photo", fileName: "photo.jpg", mimeType: "image/jpeg") 面临什么问题?【参考方案3】:

使用以下函数将带有其他参数的图像上传到服务器:

typealias MultipartFormDataBlock = (_ multipartFormData : MultipartFormData?) -> Void
typealias CompletionBlock = (_ response: Any?, _ error: Error?) -> Void

func multiPartRequestWithUrl(url: String, parameters: Dictionary<String,Any>?, multiPartFormDataBlock: MultipartFormDataBlock?, completion: CompletionBlock?) -> Void 
        var param : Dictionary! = parameters ?? Dictionary()
        print("Param = \(param)")
        Alamofire.upload(multipartFormData:  (multiPartFormData) in
            multiPartFormDataBlock?(multiPartFormData)            
            if param != nil 
                for (key, value) in param! 
                    multiPartFormData.append("\(value)".data(using: .utf8)!, withName: key)
                
            

        , to: url, encodingCompletion:encodingResult in
            switch encodingResult 
            case .success(let upload, _, _):
                upload.responseJSON  response in

                    switch response.result 
                    case .success(let value):
                        handleResponse(response: value, completion: completion)
                    case .failure(let error):
                        print(error.localizedDescription)
                        completion?(nil, error)
                    
                
            case .failure(let encodingError):
                completion?(nil, encodingError)
            

        )
    

对于 AFNetworking 的新功能

+ (NSURLSessionDataTask *)multiPartRequestWithURL:(NSString *)strUrl parameters:(NSDictionary *)parameters constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))formData progress:(void (^)(NSProgress *progress))progressBlock requestCompletionBlock:(requestCompletionBlock)requestCompletionBlock 
    NSMutableDictionary *dictParameters = [parameters mutableCopy];
    if(!dictParameters) 
        dictParameters = [NSMutableDictionary dictionary];
    
    dictParameters[@"lang"] = [AppUtility CURRENT_SELECTED_LANGUAGE];

    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:strUrl parameters:dictParameters constructingBodyWithBlock:formData error:nil];
    [request setTimeoutInterval:3600];

    NSURLSessionDataTask *dataTask = [self request:request uploadProgress:^(NSProgress *uploadProgress) 
        dispatch_async(dispatch_get_main_queue(), ^
            if(progressBlock) 
                progressBlock(uploadProgress);
            
        );
     downloadProgress:nil requestCompletionBlock:^(id responseObject, NSError *error) 
        if(requestCompletionBlock) 
                requestCompletionBlock(responseObject, error);
            
    ];
    [dataTask resume];
    return dataTask;

【讨论】:

我只使用 AFNetworking 仅 SWIFT 3 XCODE 8 ios 10 查看我编辑的答案。我添加了 AFNetworking 代码【参考方案4】:

在 Swift 4 中使用 AFNetworking 上传图片

let urlPath1 = "Path url here"

    let manager = AFHTTPRequestOperationManager()

    var Timestamp: String 
        return "\(NSDate().timeIntervalSince1970 * 1000)"
    



    let operation =  manager.post(urlPath1 as String, parameters: dictData, constructingBodyWith:  (data:AFMultipartFormData!) -> Void in

        if image != nil 

            data.appendPart(withFileData: UIImagePNGRepresentation(image!)!, name: imageName as String, fileName: "\(Timestamp).png", mimeType: "image/png")


        
    , success:  (operation, responseObject) -> Void in

        success(responseObject as AnyObject)
    )  (operation, error) -> Void in

        print(error, terminator: "")
    

    operation?.start()

【讨论】:

【参考方案5】:

在 Swift 5 中使用以下:

image.pngData()

forImage.jpegData(compressionQuality: 0.5)

根据您的要求。

【讨论】:

以上是关于如何在 Xcode 8 和 iOS 10 中使用 AFNetworking 类和 Swift 3 上传图像的主要内容,如果未能解决你的问题,请参考以下文章

clipsToBounds 导致 UIImage 在 iOS10 和 XCode 8 中不显示

如何在 xcode 5 上安装 ios 8 sdk?

Swift - Xcode 8 - iOS 10 - 无法创建简单约束

xcode 8 和 iOS 10 本地通知

使用xcode 8 调试ios10

Xcode 8 | iOS 10 模拟器“回复错误:连接无效”