Ios Swift:JSON写入(UIImage)中的类型无效

Ios Swift:JSON写入(UIImage)中的类型无效,ios,swift,uiimage,nsdata,nsurlsession,Ios,Swift,Uiimage,Nsdata,Nsurlsession,我正在尝试将UIImage转换为base 64字符串,以便将其保存到文件中,然后上载。我正在做以下工作: 代码片段: var writePath: String! var params: NSMutableDictionary = ["file1": UIImageJPEGRepresentation(self.imageView1.image!, 1.0)!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue:

我正在尝试将
UIImage
转换为
base 64
字符串,以便将其保存到文件中,然后上载。我正在做以下工作:

代码片段:

var writePath: String!
var params: NSMutableDictionary = ["file1": UIImageJPEGRepresentation(self.imageView1.image!, 1.0)!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)), "userId" : user_id]

    do {
        let bodyJson = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)
        let path: NSURL = NSURL(string: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0])!
        writePath = path.URLByAppendingPathComponent("body.data").absoluteString
        try bodyJson.writeToFile(writePath, options: .AtomicWrite)
        writePath = String(format: "file://%@", writePath)
    } catch {
        print(error)
    }
但是,我得到了无效的类型错误。我必须使用后台会话,还需要发送一些参数,所以,我使用这种方法

已解决:此问题是由其他原因造成的。

尝试解决此问题,请尝试以下操作:

    var writePath: String!
    let params: [String: String] = ["file1": UIImageJPEGRepresentation(self.imageView1.image!, 1.0)!.base64EncodedStringWithOptions(.Encoding64CharacterLineLength), "userId" : user_id]

    do {
        let bodyJson = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)
        let path: NSURL = NSURL(string: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0])!
        writePath = path.URLByAppendingPathComponent("body.data").absoluteString
        try bodyJson.writeToFile(writePath, options: .AtomicWrite)
        writePath = String(format: "file://%@", writePath)
    } catch {
        print(error)
    }

我们正在做以下工作(请原谅obj-c到swift的转换可能有点错误):

现在可以使用
NSJSONSerialization
jsonDic
转换为正确的序列化JSON


确保jsonDic键始终是字符串也是非常重要的。如果密钥不是字符串,则无法创建正确的JSON序列化对象。

能否添加错误屏幕截图?user_id是Int吗?@MarcoSantarossa user_id是字符串。我还有其他参数。它们都是字符串。您可以编写
var参数:[String:String]
。不管怎样,你能添加错误截图吗?@MarcoSantarossaI添加了截图。真奇怪。你能检查一下
params[“file”]
是否是字符串吗?我的代码和你的代码有什么区别?看起来是一样的。@karanversingh我添加了一个swift字典和编码64字符行长度选项。我没有这个代码的问题,我已经尝试过这个选项,但有相同的问题。我已将此图像保存在核心数据中。这可能是个问题吗?如果我在params dictionary外打印file1,它会像它应该做的那样打印出完整的图像,但是当我打印出完整的params dictionary时,它会打印出“size{501750}orientation 0 scale 1.000000”谢谢,我仔细检查了dictionary变量,做了一些更改,现在它正在运行Tanks,我仔细检查了dictionary变量,做了一些更改,现在它开始工作了
let data = UIImageJPEGRepresentation(img,0.5)
let base64Encoded = data.base64EncodedStringWithOptions(0)
let jsonDic = ["image" : base64Encoded]
...
...