Error "Thread 1: breakpoint 2.1" - xcode

I am working on a REST API Manager. It is giving an error and I am not able to fix it. The error I got is given below as highlighted.
import Foundation
import Alamofire
import SwiftyJSON
class RestApiManager {
var resources: JSON = [
"resources": [
"resourceA": []
]
]
let apiUrl: String
let apiUsername: String
let apiPassword: String
init(apiUrl: String, apiUsername: String, apiPassword: String) {
self.apiUrl = apiUrl
self.apiUsername = apiUsername
self.apiPassword = apiPassword
getApiResourceA() { responseObject, error in
let resourceA = JSON(responseObject!)
self.resources["resources"]["resourceA"] = resourceA
}
}
func collectDataFromApi(completionHandler: (responseObject: NSDictionary?, error: NSError?) -> ()) {
prepareHttpRequest(completionHandler)
}
func prepareHttpRequest(completionHandler: (responseObject: NSDictionary?, error: NSError?) -> ()) {
let alamofireRequest = Alamofire.request(.GET, "\(self.apiUrl)")
alamofireRequest.authenticate(user: self.apiUsername, password: self.apiPassword)
alamofireRequest.responseJSON { request, response, responseObject, error in
completionHandler(responseObject: responseObject as? NSDictionary, error: error)
}
}
func getAllResources() -> JSON {
return self.resources
}
func getApiResourceA(completion: (responseObject: NSDictionary?, error: NSError?) -> ()) {
collectDataFromApi() { responseObject, error in
completion(responseObject: responseObject, error: error)
}
}
}
And when I call this class to get the resources:
override func viewDidLoad() {
super.viewDidLoad()
if record != nil {
let url = record?.url
let username = record?.username
let password = record?.password
let restApiManager = RestApiManager(apiUrl: url!, apiUsername: username!, apiPassword: password!) // This line seems buggy
let delay = 10.0 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue()) {
let Resources = restApiManager.getAllResources()
let ResourceA = Resources["resources"]["resourceA"]
}
}
}
The line I commented prints:
Thread 1: breakpoint 2.1
I need suggestions for fix that error. Any suggestions are very much appreciated

You may have accidentally set a breakpoint without noticing.
Click and drag the blue tick representing the breakpoint outside of the gutter to erase it.

I was getting same error when I accidentally activated Breakpoint in my Xcode.
To resolve issue, simply unblock blue icon.

Related

Swift 3 - Invalid conversion from throwing function type '(Any) -> Void'

I'm new to swift and
I'm not understanding why I'm getting this error.
I've being reading similar questions and so far none of them solved this error or I have not found it:
Invalid conversion from throwing function of type '(_) throws -> ()'
to non-throwing function type '(Any) -> ()'
At the line:
self.ws.event.message = { message in
The piece of code with the error:
public var ws = WebSocket()
public func websocket(token: Any){
self.ws.open("ws://"+String(APIHOST)+":"+String(port)+"/ws?token="+String(describing: token))
self.ws.event.message = { message in
if let text = message as? String {
let json = try JSONSerialization.jsonObject(with: text, options: []) as? [String: Any]
print("recv: \(text)")
}
}
}
Thanks for any help
Try below piece of code
public var ws = WebSocket()
public func websocket(token: Any){
self.ws.open("ws://"+String(APIHOST)+":"+String(port)+"/ws?token="+String(describing: token))
self.ws.event.message = { message in
if let dataObj = message as? Data {
do {
let json = try JSONSerialization.jsonObject(with:dataObj, options: []) as? [String: Any]
print("recv: \(text)")
} catch error {
print("Unable to load data: \(error)")
}
}
}
}
If you have a function that throws something, it usually means there might be a chance of error when accessing that data in your case JSON.
If function throws you need to do {} catch {} to tell Swift you are going to handle an error.

Parse api's saveInBackground not working in Swift 3

I'm testing my parse code on Heroku because of parse.com's shutdown. In Swift 3, saveInBackgroundWithBlock has been renamed to saveInBackground, so I updated that syntax in my code as well as the 'NS' prefix issue. But an error still remains. As a learner, I can't possibly take care of this further. I want a kind person to help me solve this. Thanks in advance.
import UIKit
import Parse
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let object = PFObject(className: "testObject")
object["name"] = "Bill"
object["lastname"] = "Alexander"
object.saveInBackground(block: { (success, error) in
if success {
print("Saved in server")
} else {
print(error!)
}
})
}
Here is also my screenshot:
'Expected declaration' error screenshot
You almost there, The syntax is just slightly incorrect. Also check against the error for any issues.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let object = PFObject(className: "testObject")
object["name"] = "Bill"
object["lastname"] = "Alexander"
object.saveInBackground { (success, error) -> Void in
if error == nil {
print("Saved in server")
} else {
print(error!)
}
}
}

What does [weak self] do and what is this code structure means?

I have couple of questions about the structure of the following code.I assume progressBlock and completionhandlers are callback functions passed to downloadWithDownloadType function. Is my assumption correct? And What does [weak Self] before function parameters do? In what situation do you need that?
func downloadContent(key: String, pinOnCompletion: Bool) {
let manager = AWSUserFileManager.defaultUserFileManager()
let content = manager.contentWithKey(self.prefix + key)
content.downloadWithDownloadType(
.IfNewerExists,
pinOnCompletion: pinOnCompletion,
progressBlock: {[weak self](content: AWSContent?, progress: NSProgress?) -> Void in
guard self != nil else { return }
/* Show progress in UI. */
},
completionHandler: {[weak self](content: AWSContent?, data: NSData?, error: NSError?) -> Void in
guard self != nil else { return }
if let error = error {
// Handle Error
return
}
if let fileData = data {
let rawData = NSString(data: fileData, encoding:NSUTF8StringEncoding) as! String
// Do something
}
//Download Complete
})
}

Xcode Swift 3 NSURLSession.sharedSession

Im trying to update my basic weather app i made with swift 2 to swift 3 this is my code:
func getWeather(city: String) {
let path = "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=095711373620570aa92ee530246dc8af"
let url = NSURL(string: path)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
print(">>>> \(data)")
}
and NSURLSession.sharedSession(5th line) and NSURLResponse(6th line) print out an error
Don't annotate types in the completion handler signature and use the Swift 3 native structures:
func getWeather(city: String) {
let path = "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=095711373620570aa92ee530246dc8af"
let url = URL(string: path)
let session = URLSession.shared
let task = session.dataTask(with:url!) { (data, response, error) -> Void in
print(">>>> \(data)")
}
Swift 3 update
URLSession.shared.dataTask()

Completion handler giving: Type of expression is ambiguous without more context, after updating to swift 2

I'm using the SODA Client for swift (Created by Socrata), I just updated to XCode 7 and swift 2 and found some troubles. The one I haven't been able to solve is the completion handler case when it finds an error, it's not accepting the line "syncCompletion(.Error (reqError))" that supposedly should get the error and return to main thread.
I've seen many errors with the same description here "Type of expression is ambiguous without more context", but not in completion handlers, I saw one using do - catch that is different. I'm don't know enough of swift to find out the way to change this.
Some answers suppose you should rewrite the code because some types could have change in swift 2, but I wouldn't know where to start rewriting.
Thanks in advance for your help.
var task = session.dataTaskWithRequest(request, completionHandler: { data, response, reqError in
// We sync the callback with the main thread to make UI programming easier
let syncCompletion = { res in NSOperationQueue.mainQueue().addOperationWithBlock { completionHandler (res) } }
// Give up if there was a net error
if reqError != nil {
syncCompletion(.Error (reqError))
return
}
// Try to parse the JSON
// println(NSString (data: data, encoding: NSUTF8StringEncoding))
var jsonError: NSError?
var jsonResult: AnyObject!
do {
jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
} catch var error as NSError {
jsonError = error
jsonResult = nil
} catch {
fatalError()
}
if let error = jsonError {
syncCompletion(.Error (error))
return
}
// Interpret the JSON
if let a = jsonResult as? [[String: AnyObject]] {
syncCompletion(.Dataset (a))
}
else if let d = jsonResult as? [String: AnyObject] {
if let e : AnyObject = d["error"] {
if let m : AnyObject = d["message"] {
syncCompletion(.Error (NSError(domain: "SODA", code: 0, userInfo: ["Error": m])))
return
}
}
syncCompletion(.Dataset ([d]))
}
else {
syncCompletion(.Error (NSError(domain: "SODA", code: 0, userInfo: nil)))
}
})
Solved, I replaced:
if reqError != nil
With
if let error = reqError
and:
syncCompletion(.Error (reqError))
with
syncCompletion(.Error (error))

Resources