在Swift iOS中使用AFNetworking上传图片 [英] upload image using AFNetworking in swift ios

查看:178
本文介绍了在Swift iOS中使用AFNetworking上传图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 AFNetworking 在swift中将图像上传到服务器,但出现此错误无法读取数据,因为

I am trying to upload an image to my server using AFNetworking in swift , and I got this error The data couldn’t be read because it isn’t in the correct format.

  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")
            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)")
            })

有什么帮助吗?!

推荐答案

我正在猜测您不能使用这样的文件的任意路径。尝试从应用程序的捆绑包开始使用图像文件,然后使用NSBundle URLForResourceWithExtension之类的调用来获取文件。

I'm guessing that you can't use an arbitrary path to a file like that. Try using an image file from your app's bundle to start with, and use a call like NSBundle URLForResourceWithExtension to fetch the file.

如果要从用户的文件中加载文件相机胶卷需要使用适当的API,而不是直接文件路径。 (直接访问文件系统受到应用程序沙箱的严格限制。)

If you want to load a file from the user's camera roll you need to use the appropriate API, not a direct file path. (Direct access to the file system is severely limited by the "app sandbox".)

这篇关于在Swift iOS中使用AFNetworking上传图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆