Why is this consecutive not allowed - if-statement

I am trying to follow this appcoda GoogleMaps tutorial and converting to swift 2. I am really new to swift and having trouble understanding.
do {
let dictionary = try NSJSONSerialization.JSONObjectWithData(geocodingResultsData!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
} catch let error as NSError {
print("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]
I am getting the error before "else" where it first recommended a ";" because of consecutive statement but then it errors in the same place "expected expression". I swear I have done this before without errors. I am having trouble understanding why. Is it something to do with a poor set up of try, catch, do? Any insight appreciated, thanks.

#pirateKyle
I think you should do this way
do {
let dictionary = try NSJSONSerialization.JSONObjectWithData(geocodingResultsData!, options: NSJSONReadingOptions.MutableContainers) as! Dictionary<NSObject, AnyObject>
// 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)
}
} catch let error as NSError {
completionHandler(status: "", success: false)
print(error)
}

Related

unable to save the data in api using POST method in swift

I am not able to see the changes as per required in API, when I am using the Post method to do so can I get the correct solution. Here is the Code that I have written
#IBAction func savebutton(_ sender: Any) {
if let id1 = UserDefaults.standard.string(forKey: "Userid"),let usertype1 = UserDefaults.standard.string(forKey: "Usertype")
{
var request = URLRequest(url: URL(string: "http://www.shreetechnosolution.com/funded/donorprofile.php")!)
request.httpMethod = "POST"
let postString = "Name=\(textname.text!)&Gender=\(textGender.text!)&Email=\(textemail.text!)&MobileNo=\(textmb.text!)&Country=\(textcountry.text!)&donorid=\(id1)&usertype=\(usertype1)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
let json = try! JSONSerialization.jsonObject(with: data, options: []) as! NSDictionary
let msg = json.value(forKey: "message") as! NSString!
let alert : UIAlertView = UIAlertView(title: "Alert box!", message: "\(msg!).",delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
}
}
Can anyone help me, please?

How to parse alamofire json response in swift 3?

i am new to swift programming, i have spent considerable amount of time figuring out how to parse json response from alamofire server call. My Json response is
{"customer_info":[{"customer_id":"147","response_code":1}]}
and i want to access both variables. My swift code is
Alamofire.request(
URL_USER_REGISTER,
method: .post,
parameters: parameters,
encoding: JSONEncoding.default).responseJSON
{
if let json = response.result.value {
print (json)
}
if let result = response.result.value as? [String:Any] {
var names = [String]()
do {
if let data = data,
let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
let blogs = json["customer_info"] as? [[String: Any]] {
for blog in blogs {
if let name = blog["customer_id"] as? String {
names.append(name)
}
}
}
} catch {
print("Error deserializing JSON: \(error)")
}
print(names)
}
}
please help
Your code is parsing correctly. Add the following code to your blog loop and get the second variable out
if let response_code = blog["response_code"] as? Int {
//Do something here
}
So the complete code you are looking for is
let str = "{\"customer_info\":[{\"customer_id\":\"147\",\"response_code\":1}]}"
let data = str.data(using: .utf8)
do {
if let data = data,
let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
let blogs = json["customer_info"] as? [[String: Any]] {
for blog in blogs {
if let name = blog["customer_id"] as? String {
print(name)
}
if let response_code = blog["response_code"] as? Int {
print(response_code)
}
}
}
} catch {
print("Error deserializing JSON: \(error)")
}
i have modified the code and getting result now
if let jsonDict = response.result.value as? [String:Any],
let dataArray = jsonDict["customer_info"] as? [[String:Any]]
{
let nameArray = dataArray.flatMap { $0["customer_id"] as? String }
let nameArray2 = dataArray.flatMap { $0["response_code"] as? Int }
if(dataArray.count>0)
{
//store return customer id and response code
let customer_id_received = nameArray[0]
let response_code_received = nameArray2[0]
if(response_code_received==1)
{
//proceed with storing customer id in global variable
print(nameArray2[0])
}

Swift 3 Howto parse json from Alamofire into a model

I can't parse a json response from an Alamofire query into a model. I have this model code. What am I doing wrong? I am using Swift 3 in Xcode 8.3
enum SerializationError: Error {
case missing(String)
case invalid(String, Any)
}
struct Thing {
var id: String
var name: String
}
extension Thing {
init(json: [String: Any]) throws {
guard let id = json["id"] as? String else {
throw SerializationError.missing("id")
}
guard let name = json["name"] as? String else {
throw SerializationError.missing("name")
}
self.id = id
self.name = name
}
}
Then in my controller I have
func parseData(jsonData: [String: Any]) {
var model = [Thing]()
let things = jsonData["things"] as! [[String: Any]]
for thing in things {
do {
let aThing = try Thing(json: thing)
model.append(aThing)
} catch let error {
print(error.localizedDescription)
}
}
}
I always get an error. I know that the error isn't about the json response as I have checked it carefully and had extra code in there to test that the elements are present.
The operation couldn’t be completed. (MyApp.SerializationError error 0.)

Writing to text file in swift 3

I am trying to write data that is inputted by a user via UITextField to a text file. I am successfully able to do this by the code I have written below. However, when I tried to save more data it will replace the existing data in the textfile with the new data that is being saved. for example, if I save the string 'hello world' and then save another string saying 'bye'. I will only see the string 'bye' in the textfile. Is there a way I can modify my code so I can see 'hello world' on one line of the textile and 'bye' on another.
#IBAction func btnclicked(_ sender: Any) {
self.savedata(value: answer.text!)
}
func savedata (value: String){
let fileName = "Test"
let DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileURL = DocumentDirURL.appendingPathComponent(fileName).appendingPathExtension("txt")
print("FilePath: \(fileURL.path)")
let writeString = NSString(string: answer.text!)
do {
// Write to the file
try writeString.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8.rawValue)
} catch let error as NSError {
print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
}
}
Here is an example using FIleHandler, adapted to Swift 3, from here (of course you should add all the error handling code that's missing in my example) :
let dir = FileManager.default.urls(for: FileManager.SearchPathDirectory.cachesDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).first!
let fileurl = dir.appendingPathComponent("log.txt")
let string = "\(NSDate())\n"
let data = string.data(using: .utf8, allowLossyConversion: false)!
if FileManager.default.fileExists(atPath: fileurl.path) {
if let fileHandle = try? FileHandle(forUpdating: fileurl) {
fileHandle.seekToEndOfFile()
fileHandle.write(data)
fileHandle.closeFile()
}
} else {
try! data.write(to: fileurl, options: Data.WritingOptions.atomic)
}
do {
let fileHandle = try FileHandle(forWritingTo:pathWithFileName)
fileHandle.seekToEndOfFile()
let oldData = try String(contentsOf: pathWithFileName,encoding: .utf8).data(using: .utf8)!
var data = periodValue.data(using: .utf8)!
fileHandle.write(data)
fileHandle.closeFile()
} catch {
print("Error writing to file \(error)")
}
Here is a Swift 4 version as an extension to String.
extension String {
func writeToFile(fileName: String) {
guard let dir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first else {
return
}
let fileUrl = dir.appendingPathComponent(fileName)
guard let data = self.data(using: .utf8) else {
return
}
guard FileManager.default.fileExists(atPath: fileUrl.path) else {
try? data.write(to: fileUrl, options: .atomic)
return
}
if let fileHandle = try? FileHandle(forUpdating: fileUrl) {
fileHandle.seekToEndOfFile()
fileHandle.write(data)
fileHandle.closeFile()
}
}
}

Argument type NSURL does not conform

I am working from an old tutorial swift2, Alamofire 3, but I am using swift 3, Alamofire 4.
I have changed most things successfully, but I am running into a problem.
with this code area.
let url = NSURL(string: _pokemonUrl)!
Alamofire.request(url).responseJSON { response in
let result = response.result
I am getting an error that says:
Argument type NSURL does not conform to expected type
URLRequestConvertible.
it does give me the option of adding in as! URLRequestConvertible after the (url) but it crashes again after compile and when i press the button to get the info. it gives an error of:
Could not cast value of type 'NSURL' (0x117e99338) to
'Alamofire.URLRequestConvertible' (0x1189ab120).
if I change NSURL to Url then it moves forward in the code but when it gets to the print statement it crashes and gives the error:
fatal error: unexpectedly found nil while unwrapping an Optional value
here is that code below.
let url = URL(string: _pokemonUrl)!
Alamofire.request(url).responseJSON { response in
let result = response.result
if let dict = result.value as? Dictionary<String, AnyObject> {
if let weight = dict["weight"] as? String {
self._weight = weight
}
if let height = dict["height"] as? String {
self._height = height
}
if let baseAttack = dict["attack"] as? Int {
self._baseAttack = "\(baseAttack)"
}
if let defense = dict["defense"] as? Int {
self._defense = "\(defense)"
}
print(self._weight)
print(self._height)
print(self._baseAttack)
print(self._defense)
I have tried to change all to Int but i get the same error.
Can anyone shed any light on this for me.
if it helps I put a break point in after print("Here") in the next code and it gives me the following error.
let url = URL(string: _pokemonUrl)!
Alamofire.request(url).responseJSON { response in
let result = response.result
print(result.value.debugDescription)
print("Here")
error comes up:
Optional({
"error_message" = "Sorry, this request could not be processed. Please try again later.";
})
Here
Thanks in advance,
Tony
You almost did it guys, just a cast to URL was missing.
let nsurl = NSURL(string: _pokemonUrl)!
let request = URLRequest(url: nsurl as URL)
Alamofire.request(request).responseJSON { response in
let result = response.result
...
}
I tried folowing & it's helped
func downloadPokemonDetails(completed: DownloadComplete) {
let url = URL(string: _pokemonUrl)!
Alamofire.request(URLRequest(url: url)).responseJSON { response in
if let result = response.result.value as? [String: Any]{
print(result.debugDescription)
}
}
}