Use of unresolved identifier 'MapTasks' in Swift - objective-c

I am following tutorial, as it is pretty old tutorial and they actually used GoogleMaps framework package instead of pods which I followed and everything was going smooth till I reached Spotting a Custom Location. In that section they asked to update func geocodeAddress as below, and add var mapTasks = MapTasks() in ViewController.swift file which I did but it gives me error.
Use of unresolved identifier 'MapTasks'
error
func geocodeAddress(address: String!, withCompletionHandler completionHandler: ((status: String, success: Bool) -> Void)) {
if let lookupAddress = address {
var geocodeURLString = baseURLGeocode + "address=" + lookupAddress
geocodeURLString = geocodeURLString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
let geocodeURL = NSURL(string: geocodeURLString)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let geocodingResultsData = NSData(contentsOfURL: geocodeURL!)
var error: NSError?
let dictionary: Dictionary<NSObject, AnyObject> = NSJSONSerialization.JSONObjectWithData(geocodingResultsData!, options: NSJSONReadingOptions.MutableContainers, error: &error) as Dictionary<NSObject, AnyObject>
if (error != nil) {
println(error)
completionHandler(status: "", success: false)
}
else {
// Get the response status.
let status = dictionary["status"] as String
if status == "OK" {
let allResults = dictionary["results"] as Array<Dictionary<NSObject, AnyObject>>
self.lookupAddressResults = allResults[0]
// Keep the most important values.
self.fetchedFormattedAddress = self.lookupAddressResults["formatted_address"] as String
let geometry = self.lookupAddressResults["geometry"] as Dictionary<NSObject, AnyObject>
self.fetchedAddressLongitude = ((geometry["location"] as Dictionary<NSObject, AnyObject>)["lng"] as NSNumber).doubleValue
self.fetchedAddressLatitude = ((geometry["location"] as Dictionary<NSObject, AnyObject>)["lat"] as NSNumber).doubleValue
completionHandler(status: status, success: true)
}
else {
completionHandler(status: status, success: false)
}
}
})
}
else {
completionHandler(status: "No valid address.", success: false)
}
}
Here is my GitHub repository
Thank you in advance.

If you fully read that tutorial, you will find in the instruction that you need to create a file name MapTasks which is a class.
You can just copy this file from GitHub and add it to your project.

Related

Download APNG File

I am getting some issues related to APNG file, APNG file animation working perfect if i put APNG files in resource bundle , But when i have download same APNG file from assets server and saving APNG file into resource directory and then load using MSSticker like this way. after loading it showing only first frame.if anyone wanna try to check APNG file please have a look to this.
let imagePath = Bundle.main.path(forResource: imgName, ofType: ".png")
let pathurl = URL(fileURLWithPath: imagePath!)
do {
try cell.stickerview.sticker = MSSticker(contentsOfFileURL: pathurl, localizedDescription: "anything that you want")
}
catch {
fatalError("Failed to create sticker: \(error)")
}
Here i am saving image & getting saved image url from resource directory:
static func saveImage(image: UIImage , name:String) -> Bool? {
guard let data = UIImagePNGRepresentation(image) else {
return false
}
guard let directory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) as NSURL else {
return false
}
do {
try data.write(to: directory.appendingPathComponent(name)!)
return true
} catch {
print(error.localizedDescription)
return false
}
}
static func getSavedImageUrl(named: String) -> URL? {
if let dir = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) {
return URL(fileURLWithPath: dir.absoluteString).appendingPathComponent(named)
}
return nil
}
I have written the extension in custom MSSticker class
extension MSStickerView {
func downloadedFrom(url: URL , name: String) {
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else { return }
DispatchQueue.main.async() { () -> Void in
// self.sticker = image
_ = GameUtil.saveImage(image: image, name: name)
if let pathurl = GameUtil.getSavedImageUrl(named: name) {
do {
try self.sticker = MSSticker(contentsOfFileURL: pathurl, localizedDescription: "Raid")
}
catch {
fatalError("Failed to create sticker: \(error)")
}
}
self.startAnimating()
}
}.resume()
}
func downloadedFrom(link: String , name: String) {
guard let url = URL(string: link) else { return }
downloadedFrom(url: url ,name: name)
}
I think problem is this UIImagePNGRepresentation. Why convert Data to UIImage and then use UIImagePNGRepresentation.
Try saving data directly.
static func saveData(data: Data , name:String) -> Bool? {
guard let directory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) as NSURL else {
return false
}
do {
try data.write(to: directory.appendingPathComponent(name)!)
return true
} catch {
print(error.localizedDescription)
return false
}
}
And ignore image just pass data.
_ = GameUtil.saveImage(data: data, name: name)

Best practice to safely load image from url

I have the following code snippet to load an image from an url:
let url = NSURL(string: imageUrl)
let data = NSData(contentsOfURL: url!)
let image = UIImage(data: data!)
In case that my variable imageUrl has a valid string value, what is the most secure way to protect this code against possible edge cases?
Following code seems not to be very handy:
if let url = NSURL(string: imageUrl) {
if let data = NSData(contentsOfURL: url) {
if let image = UIImage(data: data) {
// success -> do something with the image...
}
else {
// print error message
}
}
else {
// print error message
}
}
else {
// print error message
}
The best practice is not to use a synchronous method like contentsOfURL to load data from over the network.
The recommended way is NSURLSession which works asynchronously.
This is a simple example with a completion block and an enum with associated types,
it catches all possible errors
enum Result {
case Success(UIImage), Failure(NSString)
}
func loadImage(string : String, completion: (Result) -> ()) {
guard let url = NSURL(string: string) else {
completion(.Failure("Bad URL"))
return
}
NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in
if error != nil {
completion(.Failure(error!.localizedDescription))
} else {
guard let image = UIImage(data: data!) else {
completion(.Failure("Could not load image data"))
return
}
completion(.Success(image))
}
}.resume()
}
Call it with:
loadImage("http://myserver.com/path/to/image.png") { result in
switch result {
case .Success(let image) :
// do something with the image
case .Failure(let error) :
print(error)
}
}

CloudKit ___recordID is not marked queryable

I tried to save data to the CloudKit programmatically with success but I got an error when I fetch data from CloudKit
I got an error
> <CKError 0x608000052060: "Invalid Arguments" (12/2015); server message
> = "Field '___recordID' is not marked queryable"; uuid = 19F1E556-5384-42FD-8F65-9FD8A9C9523D; container ID =
> "iCloud.com.mywebsite.CloudDemo">
This is my code.
func saveNewRecordTypeToCloud() {
// Prepare the record to save
var record = CKRecord(recordType: "Members")
record.setValue("test", forKey: "name")
record.setValue("test", forKey: "surname")
// Get iCloud Database
let cloudContainer = CKContainer.defaultContainer()
let database = CKContainer.defaultContainer().privateCloudDatabase
// Save the record to iCloud
database.saveRecord(record, completionHandler: { (record:CKRecord!, error:NSError! ) in
if error != nil {
NSLog(error.localizedDescription)
} else {
dispatch_async(dispatch_get_main_queue()) {
println("finished")
}
}
})
}
func getRecordsFromCloud() {
// Fetch data using Convenience API
let cloudContainer = CKContainer.defaultContainer()
let publicDatabase = CKContainer.defaultContainer().privateCloudDatabase
let predicate = NSPredicate(value: true)
let sort = NSSortDescriptor(key: "creationDate", ascending: false)
let query = CKQuery(recordType: "Members", predicate: predicate)
query.sortDescriptors = [sort]
publicDatabase.performQuery(query, inZoneWithID: nil, completionHandler: {
results, error in
if error == nil {
self.members = results as! [CKRecord]
println(self.members)
} else {
println(error)
}
}) }
To resolve such the problem, I had to set the Metadatas Index via Web DashBoard but I want to know if I could set the Metadatas Index by the code?
If so, please give me some code sample.
Thank you for all answers.
Sorry, there is no way to set indexes from code. You have to do this in the CloudKit dashboard.

AlamoFire with Swift 1.2: Ambiguous use of 'responseJSON'

I'm attempting to use AlamoFire with Swift 1.2 in XCode 6.3. I've fixed most of the problems (i.e. changing as to as!) but I have one that I can't figure out.
The following code - and snippets like it - generates a compile time error with the message "Ambiguous use of 'responseJSON'" at the line 5 ("req.responseJSON(){"). What do I need to change in the AlamoFire library or my code to fix it? Note: I imported the project as described in the documentation and it worked fantastic in Swift 1.1 and XCode 6.1.1
func theaters(delegate:GlobalNetworkingDelegate){
if let url = self.mainNetworkingUrl{
var urlToUse = url + "theaters"
var req:Request = Alamofire.request(.GET, urlToUse, parameters: [:], encoding: .URL)
req.responseJSON(){
(req, response, jsonOut, error) in
if(response.statusCode == 200 && error == nil){
var ajson = JSON(jsonOut!)
delegate.globalTheatersOutomce!(true, json: jsonOut, error: error)
}
}
}
}
I have also gotten the following to work:
Alamofire.manager.request(.PUT, pathWithId(user.key), parameters: user.toDict(), encoding: .JSON)
.responseString( completionHandler: {
(request: NSURLRequest, response: NSHTTPURLResponse?, responseBody: String?, error: NSError?) -> Void in
if responseBody == "OK" {
completion(user, nil)
} else {
completion(nil, error)
}
})
i.e. by explicitly stating the parameter name of the closure instead of letting it trail after the method paranthesis. It seems that the new compiler has a problem identifying the method otherwise.
Separating the trailing closure into its own variable and then calling resonseJSON(closure) fixes the problem, but I'm not sure why. Anyone have a reason? Here is the working code:
func theaters(delegate:GlobalNetworkingDelegate){
if let url = self.mainNetworkingUrl{
var urlToUse = url + "theaters"
var req:Request = Alamofire.request(.GET, urlToUse, parameters: [:], encoding: .URL)
var aClosure = {(req:NSURLRequest, response:NSHTTPURLResponse?, jsonOut:AnyObject?, error:NSError?) -> Void in
if(response!.statusCode == 200 && error == nil){
var ajson = JSON(jsonOut!)
delegate.globalTheatersOutomce!(true, json: jsonOut, error: error)
}
}
req.responseJSON(aClosure)
}
}
If you wrap the closure in () instead of leaving it trailing it works also. It works for the same reason as the other answers here, just another way to write it.
func theaters(delegate:GlobalNetworkingDelegate){
if let url = self.mainNetworkingUrl {
var urlToUse = url + "theaters"
var req:Request = Alamofire.request(.GET, urlToUse, parameters: [:], encoding: .URL)
req.responseJSON({
(req, response, jsonOut, error) in
if(response.statusCode == 200 && error == nil){
var ajson = JSON(jsonOut!)
delegate.globalTheatersOutomce!(true, json: jsonOut, error: error)
}
})
}
}
I ran into the same issue. Updating your Alamofire to the latest version (1.2.2 as the time I wrote the answer) solved the problem for me.

Missing argument for parameter #2 in call to Alamofire.request(URLRequestConvertible)

Trying to pass an Authentication header in, using the recommended approach of a custom URLRequestConvertible.
So here is my URLRequestConvertible object that conforms to the protocol:
class SecureJSONRouter : URLRequestConvertible {
var type: String
var token: String
var parameters: [String: AnyObject]
init(typevar: String, tokenvar: String, parametersvar: [String: AnyObject]) {
type = typevar
token = tokenvar
parameters = parametersvar
}
var URLRequest: NSURLRequest {
let URL = NSURL(string: da_url)!
let URLRequesting = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(type))
let encoding = Alamofire.ParameterEncoding.JSON
URLRequesting.setValue(token, forHTTPHeaderField: "Authorization")
return encoding.encode(URLRequesting, parameters: parameters).0
}
}
It's basically a place to store a few things, like a bit of URL, and a token, and a way to create a NSURLRequest with a full URL, the JSON parameters, and the header field for authorization.
When I try to call it like this:
let myUrlRequest: URLRequestConvertible = SecureJSONRouter(typevar: "locations", tokenvar: token!, parametersvar: parameters)
Alamofire.request(myUrlRequest).response{ (req, resp, data, error) in
if (error != nil) {
println(req)
println(resp)
} else {
println("saved \(data)")
}
}
it won't compile, gives me a "Missing argument for parameter #2 in call" error, at the request line.
Any ideas?
PS: I did have my SecureJSONRouter thingy as the recommended Enum instead of a Class, but I got the same error. I was looking at the protocol definition, and figured there's no reason it can't be a simpler (class) in my case, so I changed it. Still the same error.
I think there's a few possible culprits here. First off, are you sure you're calling Alamofire and not AlamoFire? I've seen people make that mistake before.
As for the sample code you posted, it didn't compile for a few different reasons. I couldn't reproduce exactly the same compiler errors you were seeing, but here's a slightly modified version of you original post that does compile.
class SecureJSONRouter : URLRequestConvertible {
var type: String
var token: String
var parameters: [String: AnyObject]
init(typevar: String, tokenvar: String, parametersvar: [String: AnyObject]) {
type = typevar
token = tokenvar
parameters = parametersvar
}
var URLRequest: NSURLRequest {
let URL = NSURL(string: "http://httpbin.org")!
let URLRequesting = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(type))
let encoding = Alamofire.ParameterEncoding.JSON
URLRequesting.setValue(token, forHTTPHeaderField: "Authorization")
return encoding.encode(URLRequesting, parameters: parameters).0
}
}
Then here's an example of calling your SecureJSONRouter.
let token: String? = "my_fancy_token"
let parameters: [String: AnyObject] = ["sample_parameter": "sample_parameter_value"]
let myUrlRequest: URLRequestConvertible = SecureJSONRouter(typevar: "locations", tokenvar: token!, parametersvar: parameters)
Alamofire.request(myUrlRequest).response{ (req, resp, data, error) in
if (error != nil) {
println(req)
println(resp)
} else {
println("saved \(data)")
}
}
That is compiling with Xcode 6.1.1 against the Alamofire 1.1.3 release. Hope that helps!