Reputation: 491
I have a ViewController, and after tap button i want get data from web.
let myClass = Class()
myClass.myMethod() {
dispatch_async(dispatch_get_main_queue()) {
}
}
In my Class file i have a method
func myMethod( completion:()->() ) {
if let connectToInternetAndGetDataFromWeb
completion()
} else {
print("Cold not construct a valid URL")
completion()
}
}
And my class to connect to internet and getting data is
func downloadJSONFromURL() {
if let httpResponse {
switch(httpResponse.statusCode) {
case 200:
// 2. Create JSON Object with data
do {
try
} catch {
print(error)
}
}
} else {
print("Error: Not a valid HTTP response")
}
dataTask!.resume()
}
And my question is how sent feedback to ViewController to show alert information from class. If i have internet connection is ok but for example when i give wrong web address i have error print("Error: Not a valid HTTP response") but how can i send this error to ViewController ?
Upvotes: 0
Views: 189
Reputation: 2550
There are multiple ways to do this.
I think the easiest part for your case is adding a closure parameter in the downloadJSONFromURL()
.
func downloadJSONFromURL(completion:((error:NSError?)->Void)) {
if let httpResponse {
switch(httpResponse.statusCode) {
case 200:
// 2. Create JSON Object with data
do {
try
completion(nil)
} catch {
print(error)
completion(error)
}
}
} else {
print("Error: Not a valid HTTP response")
}
dataTask!.resume()
}
Of course you have to chain the completion closure up to your UIViewController
that is making the request. So the myMethod
also gets an optional error parameter in it's closure and so on.
In the end you have your UIViewController class like this
let myClass = Class()
myClass.myMethod() {(error:NSError?) -> Void in
dispatch_async(dispatch_get_main_queue()) {
//Show Alert or whatever is necessary for the error
}
}
Upvotes: 0