I was using swift 1.2 and everything was going fine. after upgrading my Xcode to 7 . I faced some weird problems.
My code was :
let postData : AnyObject = ["username":username , "password":password] ;
I need this variable to be AnyObject, because
let jsonObject : AnyObject = postData ;
let jsonString = JSONStringify(jsonObject)
let data1 = jsonString.dataUsingEncoding(NSUTF8StringEncoding)
let task1 = NSURLSession.sharedSession().uploadTaskWithRequest(request, fromData: data1) {
(Data, Response, Error) -> Void in
needs a Anyobject for post Data header.
The error is
Value of type '[String : String?]' does not conform to specified type 'AnyObject'
can any one help me?
The problem is your password variable is an Optional<String>
. This means the conversion from Swift dictionary to AnyObject (I think it tries to convert it to an NSDictionary) will fail.
If you do
let postData : AnyObject = ["username":username , "password":password!]
It should work unless the password is nil (check that before creating the dictionary)
If you want to be able to have null passwords in the output, you can do this in your dictionary
let postData : [String : AnyObject] = ["username":username , "password":password ?? NSNull()]
The following works
let pw: String? = "pw"
let pw2: String? = nil
var foo: [String : AnyObject] = ["bar" : pw ?? NSNull(), "baz" : pw2 ?? NSNull()]
let data = try NSJSONSerialization.dataWithJSONObject(foo, options: NSJSONWritingOptions.PrettyPrinted)
let str = NSString(data: data, encoding: NSUTF8StringEncoding)!
print(str)
And prints
{
"baz" : null,
"bar" : "pw"
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments