Parse load Images Swift 3.0 - parse-platform

I'm runnig my own parse server and all works fine but
I can't convert A PFFile to a UIImage, this is the error it throws at me:
Cannot convert value of type '(NSData?, NSError?) -> Void' to expected argument type PFDataResultBlock'
Here is the code I used:
var imageFromParse = object.object(forKey: "ProfilePicture") as! PFFile!
imageFromParse!.getDataInBackgroundWithBlock({ (imageData: NSData?, error: NSError?) -> Void in
var image: UIImage! = UIImage(data: imageData!)!
})
And all of this used to work perfectly in Swift 2.3.
thank you for the help.

Swift 3.0:
if let imageFromParse = user.object(forKey: "ProfilePicture") as? PFFile {
imageFromParse.getDataInBackground(block: {
(data: Data?, error: Error?) in
if error == nil {
}
})
}
Main updates:
(data: NSData?, error: NSError?) in
has been updated to:
(data: Data?, error: Error?) in
And:
Swift 3 makes all labels required unless you specify otherwise, which means the method names no longer detail their parameters. In practice, this often means the last part of the method name gets moved to be the name of the first parameter.
Find out more at: https://www.hackingwithswift.com/swift3

Use Data and Error instead of NSData and NSError

i did some test on swift 3.0 and the following code works for me:
let query = PFQuery(className: "FileTest")
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
let firstObject = objects?.first as PFObject!
let objectFile = firstObject.objectForKey("file") as! PFFile
objectFile.getDataInBackgroundWithBlock({ (imageData: NSData?, error: NSError?) -> Void in
let image = UIImage(data: imageData!)
if image != nil {
self.imageOutlet.image = image
}
})
}
In this code i first fetch all the FileTest collection, then i take the first object (just for test of course) and then i read the file. please notice that i an using objectForKey in order to get the PFFile which exist under the test column. After i have the file i call getDataInBackground to get the data, create UIImage from the data and update my imageView
Everything works as expected..
try to run this code and see if it works for you.

Related

Swift: Could not cast value of type 'Could not cast value of type '__NSCFString' (0x10e4d5ef0) to 'NSDictionary' (0x10e4d6bc0).'

I am trying to get post data in dictionary. Let first me show what I am doing.
manager.POST(url, parameters: dict,
success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
if let jsonDict = self.parseJSON(responseObject) {
print(jsonDict)
// Error occur on the following line
let dataDict = jsonDict["data"] as! [String : AnyObject]
// Error Info: Swift: Could not cast value of type 'Could not cast value of type '__NSCFString' (0x10e4d5ef0) to 'NSDictionary' (0x10e4d6bc0).'
}
ParseJson Function:
func parseJSON(inputData: AnyObject) -> Dictionary<String,AnyObject>?{
do {
let jsonDict = try NSJSONSerialization.JSONObjectWithData(inputData as! NSData, options:NSJSONReadingOptions.MutableContainers) as! Dictionary<String,AnyObject>
// use jsonData
return jsonDict
} catch let error as NSError {
// report error
print(error.description)
print("Session: Json Parse Error!!!")
return nil
}
}
This is the result of pirnt(jsonDict)
[data: {"session_id":"ab4kn9fj34ko89kjkl5ljs98gfk498fgkl409alk34l","user_info":{"username":"Johny Cage","ENCPASSWORD":"johnycage","id":1,"FULLNAME":"Johny Cage"}}, status: Success]
Any help or suggestion is highly appreciated.
Check your return data from web-service. I think you are converting it in Jason String multiple times, Or something like this. There is no issue in above code. Check your server side.

AFNetworking 3 and Swift 2- Cannot convert value NSURLSessionDataTask

When trying to access the GET function from AFHTTPSessionManager from , I get error, inputing the operation:
"Cannot convert value of type '(NSURLSessionDataTask!, AnyObject!) -> Void' to expected argument type '((NSURLSessionDataTask, AnyObject?) -> Void)?'"
return self.GET("search", parameters: parameters, success: {(operation:NSURLSessionDataTask!, response:AnyObject!) -> Void in
let dictionaries = response["businesses"] as? [NSDictionary]
if dictionaries != nil {
completion(Business.businesses(array: dictionaries!), nil)
self.appDelegate.businessesLoaded = true
}
}, failure: { (operation: AFHTTPSessionManager?, error: NSError!) -> Void in
completion(nil, error)
})!
AFHTTPSessionManager.m GET function:
- (NSURLSessionDataTask *)GET:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
return [self GET:URLString parameters:parameters progress:nil success:success failure:failure];
}
This all used to work with AFHTTPRequestOperation, which is no longer part of AFNetworking 3 from deprecated NSURLConnection. Hope someone can shed some light on this and thank you very much in advance!

Swift - load image from URL [duplicate]

This question already has answers here:
Loading/Downloading image from URL on Swift
(39 answers)
Closed 6 years ago.
I'm creating a medicine database as practice and I would like to load image of pills from URLs.
Here is part of my code and it says
Cannot convert value of type '(NSURLResponse!, NSData!, NSError!) -> Void' to expected argument type '(NSURLResponse?, NSData?, NSError?) -> Void'
How am I supposed to fix it ?
Thank you!
func img_URL(urlString:String)
{
var imgURL: NSURL = NSURL(string: urlString)!
let request: NSURLRequest = NSURLRequest(URL: imgURL)
NSURLConnection.sendAsynchronousRequest(
request, queue: NSOperationQueue.mainQueue(),
completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
if error == nil {
self.pillsImage.image = UIImage(data: data)
}
})
}
completionHandler: {(response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
will solve your issue
Do what the error message tells you! Change
completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
to
completionHandler: {(response: NSURLResponse?,data: NSData?,error: NSError?) -> Void in
Even better, abandon NSURLConnection. It is replaced by NSURLSession. The call you are making is deprecated and will be removed in a future system update (possibly as soon as this June).

Extra argument 'error' in call - swift 2 [duplicate]

I'm currently developing my first iOS app using Swift 2.0 and Xcode Beta 2. It reads an external JSON and generates a list in a table view with the data. However, I'm getting a strange little error that I can't seem to fix:
Extra argument 'error' in call
Here is a snippet of my code:
let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
print("Task completed")
if(error != nil){
print(error!.localizedDescription)
}
var err: NSError?
if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary{
if(err != nil){
print("JSON Error \(err!.localizedDescription)")
}
if let results: NSArray = jsonResult["results"] as? NSArray{
dispatch_async(dispatch_get_main_queue(), {
self.tableData = results
self.appsTableView!.reloadData()
})
}
}
})
The error is thrown at this line:
if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary{
Can someone please tell me what I'm doing wrong here?
With Swift 2, the signature for NSJSONSerialization has changed, to conform to the new error handling system.
Here's an example of how to use it:
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary {
print(jsonResult)
}
} catch let error as NSError {
print(error.localizedDescription)
}
With Swift 3, the name of NSJSONSerialization and its methods have changed, according to the Swift API Design Guidelines.
Here's the same example:
do {
if let jsonResult = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject] {
print(jsonResult)
}
} catch let error as NSError {
print(error.localizedDescription)
}
Things have changed in Swift 2, methods that accepted an error parameter were transformed into methods that throw that error instead of returning it via an inout parameter. By looking at the Apple documentation:
HANDLING ERRORS IN SWIFT:
In Swift, this method returns a nonoptional result and is marked with the throws keyword to indicate that it throws an error in cases of failure.
You call this method in a try expression and handle any errors in the catch clauses of a do statement, as described in Error Handling in The Swift Programming Language (Swift 2.1) and Error Handling in Using Swift with Cocoa and Objective-C (Swift 2.1).
The shortest solution would be to use try? which returns nil if an error occurs:
let message = try? NSJSONSerialization.JSONObjectWithData(receivedData, options:.AllowFragments)
if let dict = message as? NSDictionary {
// ... process the data
}
If you're also interested into the error, you can use a do/catch:
do {
let message = try NSJSONSerialization.JSONObjectWithData(receivedData, options:.AllowFragments)
if let dict = message as? NSDictionary {
// ... process the data
}
} catch let error as NSError {
print("An error occurred: \(error)")
}
This has been changed in Swift 3.0.
do{
if let responseObj = try JSONSerialization.jsonObject(with: results, options: .allowFragments) as? NSDictionary{
if JSONSerialization.isValidJSONObject(responseObj){
//Do your stuff here
}
else{
//Handle error
}
}
else{
//Do your stuff here
}
}
catch let error as NSError {
print("An error occurred: \(error)") }

Signing Up Parse User with Swift 1.2

I use the signing up feature of Parse.com just as describe here. Here's my code:
user.signUpInBackgroundWithBlock {
(succeeded: Bool!, error: NSError!) -> Void in
if error == nil {
// Hooray! Let them use the app now.
} else {
let errorString = error.userInfo["error"] as NSString
// Show the errorString somewhere and let the user try again.
}
}
}
Unfortunately, I've updated my project from swift 1.1 to swift 1.2 and get the following compiler error:
Function signature '(Bool!, NSError!)->void is not compatible with
excepted type '#objc_block (Bool,NSError!)->Void'
it's on the following line:
user.signUpInBackgroundWithBlock {
(succeeded: Bool!, error: NSError!) -> Void in
Does anybody know how can I fox that ? Thanks !
Your succeeded variable is a 'Bool!' but what the block returns is a 'Bool' (without exclamation mark).
The solution would be:
user.signUpInBackgroundWithBlock {
(succeeded: Bool, error: NSError!) -> Void in
if error == nil {
// Hooray! Let them use the app now.
} else {
let errorString = error.userInfo["error"] as NSString
// Show the errorString somewhere and let the user try again.
}
}
}
Too see more about optionals go to the apple doc
I had the same problem with save in background with block. It looks like parse returns a "Bool not a Bool!"...however error is an NSError? unless you "!" it.
something.saveInBackgroundWithBlock {
(succeeded: Bool, error: NSError?) -> Void in
code
}

Resources