How Can I upload image on server side using json post method in swift 3 - swift3

I want to upload an image to serverside but I'm facing a problem with it. Here is the code I have written for it:
import UIKit
class ViewControllerngodetails: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate {
#IBOutlet weak var imageviewngo: UIImageView!
#IBOutlet weak var Textngo: UITextField!
#IBOutlet weak var textparentorg: UITextField!
#IBOutlet weak var texttreasurer: UITextField!
#IBOutlet weak var textsecratary: UITextField!
#IBOutlet weak var textchairman: UITextField!
#IBOutlet weak var textcheiffunction: UITextField!
#IBOutlet weak var textngoname: UITextField!
var t = NGOdetails()
//var temp1 = Int()
var img : UIImage!
var picker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
textngoname.text = t.Nameofngo
textchairman.text = t.NameofChairman
textparentorg.text = t.ParentOrganization
textsecratary.text = t.NameofSeceratary
texttreasurer.text = t.NameofTreasurer
textcheiffunction.text = t.NameofChiefFunctionary
Textngo.text = t.AboutNGO
self.textngoname.delegate = self
self.textchairman.delegate = self
self.textcheiffunction.delegate = self
self.textsecratary.delegate = self
self.texttreasurer.delegate = self
self.textparentorg.delegate = self
self.Textngo.delegate = self
// Do any additional setup after loading the view.
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func update_button(_ sender: Any) {
picker.sourceType = UIImagePickerControllerSourceType.savedPhotosAlbum
picker.delegate = self
self.present(picker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
img = info[UIImagePickerControllerOriginalImage] as! UIImage
self.imageviewngo.image = img
self.dismiss(animated: true, completion: nil)
}
#IBAction func savebutton(_ sender: Any) {
myImageuploadrequest()
}
func myImageuploadrequest()
{
let id = UserDefaults.standard.string(forKey: "NgoId")
var request = URLRequest(url: URL(string: "http://www.shreetechnosolution.com/funded/ngo_profileupdate.php?")!)
request.httpMethod = "POST"
let param = ["Nameofngo" : "\(textngoname.text!)","NameofChiefFunctionary" : "\(textcheiffunction.text!)","NameofChairman" : "\(textchairman.text!)","NameofSeceratary" : "\(textsecratary.text!)","NameofTreasurer" : "\(texttreasurer.text!)","photoofNGO" : "\(img)","ParentOrganization" : "\(textparentorg.text!)","AboutNGO" : "\(Textngo.text!)","ngoid" : "\(id!)","value" : "NGO Details"]
//"photoofNGO" : "\(imageviewngo.image!)",
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let imageData = UIImageJPEGRepresentation(imageviewngo.image!, 1)
if(imageData==nil) { return; }
// request.httpBody = createBodyWithParameters(parameters: param, filePathKey: "file", imageDataKey: imageData! as NSData, boundary: boundary) as Data
request.httpBody = self.createBodyWithParameters(parameters: param as [String : NSObject], filePathKey: "file", boundary: self.generateBoundaryString()) as Data
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
// You can print out response object
print("******* response = \(response)")
// Print out reponse body
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("****** response data = \(responseString!)")
do {
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
print(json ?? "")
DispatchQueue.main.async(execute: {
self.imageviewngo.image = nil;
});
}catch
{
print(error)
}
}
task.resume()
}
//, imageDataKey: NSData
func createBodyWithParameters(parameters: [String: NSObject]?, filePathKey: String?, boundary: String) -> NSData {
let body = NSMutableData();
if parameters != nil {
for (key, value) in parameters! {
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString(string: "\(value)\r\n")
}
}
body.appendString(string: "--\(boundary)\r\n")
let filename = "user-profile.jpg"
let mimetype = "image/jpg"
let imageData = UIImageJPEGRepresentation(img, 1)
body.appendString(string: "Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
// body.append(imageDataKey as Data)
body.appendString(string: "\r\n")
body.appendString(string: "--\(boundary)--\r\n")
return body
}
func generateBoundaryString() -> String {
return "Boundary-\(NSUUID().uuidString)"
}
}
extension NSMutableData {
func appendString(string: String) {
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
append(data!)
}
}

Related

Convert HTML text to displayable text in swiftUI [duplicate]

I was wondering how can HTML tags be stripped out of JSON from a web url. Do I have to use NSString of something similar.
So I am looking to strip out the html tags that are in the summary value. I looked around abit and it says NSString can be used but I was not sure if that was something that could be implemented into Swift 3. Any Help would be appreciated.
My code:
import UIKit
import Alamofire
struct postinput {
let mainImage : UIImage!
let name : String!
let author : String!
let summary : String!
}
class TableViewController: UITableViewController {
var postsinput = [postinput]()
var mainURL = "https://www.example.com/api"
typealias JSONstandard = [String : AnyObject]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
callAlamo(url: mainURL)
}
func callAlamo(url : String){
Alamofire.request(url).responseJSON(completionHandler: {
response in
self.parseData(JSONData: response.data!)
})
}
func parseData(JSONData : Data) {
do {
var readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONstandard
// print(readableJSON)
if let posts = readableJSON["posts"] as? [JSONstandard] {
for post in posts {
let title = post["title"] as! String
let author = post["author"] as! String
guard let dic = post["summary"] as? [String: Any], let summary = dic["value"] as? String else {
return
}
print(author)
if let imageUrl = post["image"] as? String {
let mainImageURL = URL(string: imageUrl )
let mainImageData = NSData(contentsOf: mainImageURL!)
let mainImage = UIImage(data: mainImageData as! Data)
postsinput.append(postinput.init(mainImage: mainImage, name: title, author: author, summary: summary))
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
catch {
print(error)
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return postsinput.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
// cell?.textLabel?.text = titles[indexPath.row]
let mainImageView = cell?.viewWithTag(2) as! UIImageView
mainImageView.image = postsinput[indexPath.row].mainImage
//(cell?.viewWithTag(2) as! UIImageView).image = postsinput[indexPath.row].mainImage
let mainLabel = cell?.viewWithTag(1) as! UILabel
mainLabel.text = postsinput[indexPath.row].name
mainLabel.font = UIFont(name: "Helvetica", size:14)
let autLabel = cell?.viewWithTag(3) as! UILabel
autLabel.text = postsinput[indexPath.row].author
autLabel.font = UIFont(name: "Helvetica", size:12)
let sumLabel = cell?.viewWithTag(4) as! UILabel
sumLabel.text = postsinput[indexPath.row].summary
sumLabel.font = UIFont(name: "Helvetica", size:12)
//(cell?.viewWithTag(3) as! UILabel).text = postsinput[indexPath.row].author
return cell!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You can use this code for stripping html tags
From your previous question
guard let dic = post["summary"] as? [String: Any], let summary = dic["value"] as? String else {
return
}
let str = summary.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)
print(str)
Edit
I have checked it and it is working
let summary = "<p>Latin text here</p>"
let str = summary.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)
print(str)
Latin text here

Image capture from camera and gallery in swift

I am trying to get image from camera and show in imageview using swift 3.0 but it is showing white background only. Image is uploaded to my server successfully. On iPAD it is not even opening the camera app. below is my code: I am new to swift to please let me know what mistake i ma doing.
import UIKit
import Alamofire
import SwiftyJSON
import AlamofireImage
class RadiologyViewController:UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextViewDelegate{
#IBOutlet weak var indicator1: UIActivityIndicatorView!
#IBOutlet weak var name : UILabel!
#IBOutlet weak var mobile: UILabel!
#IBOutlet weak var gender: UILabel!
#IBOutlet weak var age : UILabel!
#IBOutlet weak var indicator4: UIActivityIndicatorView!
#IBOutlet weak var indicator3: UIActivityIndicatorView!
#IBOutlet weak var indicator2: UIActivityIndicatorView!
#IBOutlet weak var pic4text: UITextView!
#IBOutlet weak var pic3text: UITextView!
#IBOutlet weak var pic2text: UITextView!
#IBOutlet weak var pictext1: UITextView!
// WHICH SHOW BUTTON YOU WANT TO SHOW YOU HAVE TO CHANGE HEIGHT CONSTRAINT //
// conPic1height = conPic1height - 20 - UN HIDE BUTTON BY TAKING ITS OUTLET//
#IBOutlet weak var conPic1height: NSLayoutConstraint!
#IBOutlet weak var conPic2height: NSLayoutConstraint!
#IBOutlet weak var conPic3height: NSLayoutConstraint!
#IBOutlet weak var conPic4height: NSLayoutConstraint!
#IBOutlet weak var pic4: UIImageView!
#IBOutlet weak var pic3: UIImageView!
#IBOutlet weak var pic2: UIImageView!
#IBOutlet weak var pic1: UIImageView!
#IBOutlet weak var complain: UILabel!
#IBOutlet weak var explain : UILabel!
#IBOutlet weak var date : UILabel!
#IBOutlet weak var btnShowPic4: UIButton!
#IBOutlet weak var btnShowPic3: UIButton!
#IBOutlet weak var btnShowPic2: UIButton!
#IBOutlet weak var btnShowPic1: UIButton!
var patient : Patients? = nil;
var username : String? = nil;
var picNumber : Int = 0;
var pic1path : String = "";
var pic2path : String = "";
var pic3path : String = "";
var pic4path : String = "";
var strLabel = UILabel()
var indicator = UIActivityIndicatorView()
let effectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.isNavigationBarHidden = true
if patient != nil {
name.text = patient?.patientName;
age.text = "Age: "+(patient?.patientAge)!;
gender.text = "Gender: "+(patient?.patientGender)!;
mobile.text = "Mobile: "+(patient?.patientMobile)!;
date.text = "Date: "+(patient?.patientDate)!;
complain.text = "Complaint: " + "\(self.makeComplainText(complain: (patient?.patientComplaint)!))";
explain.text = "Explain: "+(patient?.patientExplainComplaint)!;
}
let defaults1 = UserDefaults.standard
let user = defaults1.object(forKey: "user") as? NSData
let responseData = NSKeyedUnarchiver.unarchiveObject(with: user! as Data) as? ResponseModel
if responseData != nil {
if responseData?.profile != nil {
username = responseData?.profile[0].userName;
}
}
pictext1.delegate = self
pic2text.delegate = self
pic3text.delegate = self
pic4text.delegate = self
pic1path = (patient?.patientPic1)!;
pic2path = (patient?.patientPic2)!;
pic3path = (patient?.patientPic3)!;
pic4path = (patient?.patientPic4)!;
pictext1.text = patient?.patientPictxt1;
pic2text.text = patient?.patientPictxt2;
pic3text.text = patient?.patientPictxt3;
pic4text.text = patient?.patientPictxt4;
let tapFirstGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped1(_:)))
pic1.isUserInteractionEnabled = true
pic1.addGestureRecognizer(tapFirstGestureRecognizer)
let tapSecondGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped2(_:)))
pic2.isUserInteractionEnabled = true
pic2.addGestureRecognizer(tapSecondGestureRecognizer)
let tapThirdGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped3(_:)))
pic3.isUserInteractionEnabled = true
pic3.addGestureRecognizer(tapThirdGestureRecognizer)
let tapFourGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped4(_:)))
pic4.isUserInteractionEnabled = true
pic4.addGestureRecognizer(tapFourGestureRecognizer)
if patient?.patientPic1 != "" {
pic1.image = nil;
setImage(imageview: pic1, url: (patient?.patientPic1)!,indicator:indicator1)
showFirstButton(show: false)
} else {
showFirstButton(show: true)
indicator1.isHidden = true
}
if patient?.patientPic2 != "" {
pic2.image = nil;
showSecondButton(show: false)
setImage(imageview: pic2, url: (patient?.patientPic2)!,indicator:indicator2)
} else {
showSecondButton(show: true)
indicator2.isHidden = true
}
if patient?.patientPic3 != "" {
pic3.image = nil;
showThreeButton(show: false)
setImage(imageview: pic3, url: (patient?.patientPic3)!,indicator:indicator3)
} else {
showThreeButton(show: true)
indicator3.isHidden = true
}
if patient?.patientPic4 != "" {
pic4.image = nil;
showFourButton(show: false)
setImage(imageview: pic4, url: (patient?.patientPic4)!,indicator:indicator4)
} else {
showFourButton(show: true)
indicator4.isHidden = true
}
let tapKeuboardDismissGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard(_:)))
view.isUserInteractionEnabled = true
view.addGestureRecognizer(tapKeuboardDismissGestureRecognizer)
// Do any additional setup after loading the view.
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "\n" // Recognizes enter key in keyboard
{
textView.resignFirstResponder()
return false
}
return true
}
func dismissKeyboard(_ sender: UITapGestureRecognizer) {
view.endEditing(true)
}
func imageTapped1(_ sender: UITapGestureRecognizer) {
if (sender.view as? UIImageView) != nil {
print("Image Tapped")
picNumber = 1;
showActionSheet()
}
}
func imageTapped2(_ sender: UITapGestureRecognizer) {
if (sender.view as? UIImageView) != nil {
print("Image Tapped")
picNumber = 2;
showActionSheet()
}
}
func imageTapped3(_ sender: UITapGestureRecognizer) {
if (sender.view as? UIImageView) != nil {
print("Image Tapped")
picNumber = 3;
showActionSheet()
}
}
func imageTapped4(_ sender: UITapGestureRecognizer) {
if (sender.view as? UIImageView) != nil {
print("Image Tapped")
picNumber = 4;
showActionSheet()
}
}
func camera()
{
let myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.allowsEditing = false
myPickerController.sourceType = UIImagePickerControllerSourceType.camera
myPickerController.cameraCaptureMode = .photo
myPickerController.modalPresentationStyle = .fullScreen
self.present(myPickerController, animated: true, completion: nil)
}
func photoLibrary()
{
let myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerControllerSourceType.photoLibrary
self.present(myPickerController, animated: true, completion: nil)
}
func showActionSheet() {
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
actionSheet.addAction(UIAlertAction(title: "Camera", style: UIAlertActionStyle.default, handler: { (alert:UIAlertAction!) -> Void in
self.camera()
}))
actionSheet.addAction(UIAlertAction(title: "Gallery", style: UIAlertActionStyle.default, handler: { (alert:UIAlertAction!) -> Void in
self.photoLibrary()
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil))
// if (UIDevice.current.userInterfaceIdiom == .pad) {
// let popover = actionSheet.popoverPresentationController
// popover?.sourceRect = self.view.bounds
// popover?.sourceView = self.pic1
// popover?.permittedArrowDirections = .any
// self.present(actionSheet, animated: true, completion: nil)
// } else {
self.present(actionSheet, animated: true, completion: nil)
//}
}
#IBAction func btnpic3Click(_ sender: Any) {
var profileStoryBoard: UIStoryboard!
profileStoryBoard = UIStoryboard(name:"\(Helper.manageStoryBoardName())ShowImage",bundle: nil)
let viewcontroller : ImageShowViewController = profileStoryBoard.instantiateViewController(withIdentifier: "ImageShowViewController") as! ImageShowViewController
viewcontroller.url = pic3path
self.present(viewcontroller, animated: false)
}
#IBAction func btnpic4Click(_ sender: Any) {
var profileStoryBoard: UIStoryboard!
profileStoryBoard = UIStoryboard(name:"\(Helper.manageStoryBoardName())ShowImage",bundle: nil)
let viewcontroller : ImageShowViewController = profileStoryBoard.instantiateViewController(withIdentifier: "ImageShowViewController") as! ImageShowViewController
viewcontroller.url = pic4path
self.present(viewcontroller, animated: false)
}
#IBAction func btnpic1Click(_ sender: UIButton) {
var profileStoryBoard: UIStoryboard!
profileStoryBoard = UIStoryboard(name:"\(Helper.manageStoryBoardName())ShowImage",bundle: nil)
let viewcontroller : ImageShowViewController = profileStoryBoard.instantiateViewController(withIdentifier: "ImageShowViewController") as! ImageShowViewController
viewcontroller.url = pic1path
self.present(viewcontroller, animated: false)
}
#IBAction func btnpic2Click(_ sender: UIButton) {
var profileStoryBoard: UIStoryboard!
profileStoryBoard = UIStoryboard(name:"\(Helper.manageStoryBoardName())ShowImage",bundle: nil)
let viewcontroller : ImageShowViewController = profileStoryBoard.instantiateViewController(withIdentifier: "ImageShowViewController") as! ImageShowViewController
viewcontroller.url = pic2path
self.present(viewcontroller, animated: false)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if picNumber == 1 {
pic1.image = info[UIImagePickerControllerOriginalImage] as? UIImage
uploadImage(image: (info[UIImagePickerControllerOriginalImage] as? UIImage)!)
} else if picNumber == 2 {
pic2.image = info[UIImagePickerControllerOriginalImage] as? UIImage
uploadImage(image: (info[UIImagePickerControllerOriginalImage] as? UIImage)!)
} else if picNumber == 3 {
pic3.image = info[UIImagePickerControllerOriginalImage] as? UIImage
uploadImage(image: (info[UIImagePickerControllerOriginalImage] as? UIImage)!)
} else {
pic4.image = info[UIImagePickerControllerOriginalImage] as? UIImage
uploadImage(image: (info[UIImagePickerControllerOriginalImage] as? UIImage)!)
}
self.dismiss(animated: true, completion: nil)
}
func uploadImage(image:UIImage) -> Void {
if Reachability.isConnectedToNetwork() == true {
self.showLoading(title: "uploding image");
let imgData = UIImageJPEGRepresentation(image, 0.2)!
var path :String = "";
let parameters = ["username": username]
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imgData, withName: "images",fileName: "file.jpg", mimeType: "image/jpg")
for (key, value) in parameters {
multipartFormData.append((value?.data(using: String.Encoding.utf8)!)!, withName: key)
}
},
to:"http://www.dentalsa.net/api/api.php?method=radiaolog_image_update")
{ (result) in
switch result {
case .success(let upload, _, _):
upload.responseJSON { response in
self.hideLoading()
let value = response.result.value
let jsonResponse = JSON(value)
let status = jsonResponse["status"].stringValue
let message = jsonResponse["message"].stringValue
if status == "false" {
self.showAlerError(titleText: "Error", messagetext: message);
}
path = jsonResponse["path"].stringValue
if self.picNumber == 1 {
self.pic1path = path
} else if self.picNumber == 2 {
self.pic2path = path
} else if self.picNumber == 3 {
self.pic3path = path
} else if self.picNumber == 4 {
self.pic4path = path
}
print("ImagePath"+path)
}
case .failure(let encodingError):
print(encodingError)
}
}
} else {
self.showAlerError(titleText: "Error", messagetext: "Please check Internet connectivity");
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func makeComplainText(complain:String) -> String {
let characters = Array(complain.characters);
var data="";
if characters[0] == "1" {
data += "Check-Up, ";
}
if characters[1] == "1" {
data += "Teeth Cleaning, ";
}
if characters[2] == "1" {
data += "Periodontal Treatment, ";
}
if characters[3] == "1" {
data += "Dental Fillings, ";
}
if characters[4] == "1" {
data += "Prothesis, ";
}
if characters[5] == "1" {
data += "Extraction, ";
}
if characters[6] == "1" {
data += "Hollywoods smile, ";
}
if characters[7] == "1" {
data += "Children's Teeth, ";
}
if characters[8] == "1" {
data += "Bleaching, ";
}
return data;
}
#IBAction func saveClick(_ sender: UIButton) {
let netowrk = NetworkCall();
if Reachability.isConnectedToNetwork() == true {
self.showLoading(title: "Please wait")
netowrk.radiologyUpdate(username: username!,patientId: (patient?.patientID)!,picText1: pictext1.text!,picText2: pic2text.text!,picText3: pic3text.text!,picText4: pic4text.text!,pic1:pic1path,pic2:pic2path,pic3:pic3path,pic4:pic4path) { responseObject in
self.hideLoading()
if responseObject.status == "true" {
print("Success view controller");
self.showAlerError(titleText: "Success", messagetext: "Details saved Successfully");
} else {
self.showAlerError(titleText: "Error", messagetext: responseObject.message!);
}
return
}
} else {
self.showAlerError(titleText: "Error", messagetext: "Please check Internet connectivity");
}
}
func showLoading(title: String) {
strLabel.removeFromSuperview()
indicator.removeFromSuperview()
effectView.removeFromSuperview()
strLabel = UILabel(frame: CGRect(x: 50, y: 0, width: 160, height: 46))
strLabel.text = title
strLabel.font = UIFont.systemFont(ofSize: 14, weight: UIFontWeightMedium)
strLabel.textColor = UIColor(white: 0.9, alpha: 0.7)
effectView.frame = CGRect(x: view.frame.midX - strLabel.frame.width/2, y: view.frame.midY - strLabel.frame.height/2 , width: 160, height: 46)
effectView.layer.cornerRadius = 15
effectView.layer.masksToBounds = true
indicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
indicator.frame = CGRect(x: 0, y: 0, width: 46, height: 46)
indicator.startAnimating()
effectView.addSubview(indicator)
effectView.addSubview(strLabel)
view.addSubview(effectView)
}
func setImage(imageview :UIImageView,url:String,indicator:UIActivityIndicatorView) -> Void {
Alamofire.request("http://www.dentalsa.net"+url).responseImage { response in
if let image = response.result.value {
indicator.isHidden = true
imageview.image = image
}
}
}
func hideLoading() {
self.effectView.removeFromSuperview()
//indicator.stopAnimating()
}
func showAlerError(titleText:String,messagetext:String) {
let alertController = UIAlertController(title: titleText, message:
messagetext, preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: nil))
self.present(alertController, animated: true, completion: nil)
}
#IBAction func backClick(_ sender: UIButton) {
_ = self.navigationController?.popViewController(animated: true)
}
func showFirstButton(show :Bool){
//conPic1height.constant = 150
btnShowPic1.isHidden = show
self.view.layoutIfNeeded()
}
func showSecondButton(show :Bool){
//conPic1height.constant = 150
btnShowPic2.isHidden = show
self.view.layoutIfNeeded()
}
func showThreeButton(show :Bool){
//conPic1height.constant = 150
btnShowPic3.isHidden = show
self.view.layoutIfNeeded()
}
func showFourButton(show :Bool){
//conPic1height.constant = 150
btnShowPic4.isHidden = show
self.view.layoutIfNeeded()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
I need to capture image from camera and gallery on both iphone and iPad. I don't know what is the issue which i am facing here.

UILabel data to UIAlert issue in xcode 8, error

I made an alert and I tried to follow a tutorial and put it into my code. I put the code in a few different places but the errors just kept getting worse. I finally just put it at the bottom, because thats where I ended up getting the fewest errors. I'm new to xcode so this very basic thing is very hard for me. Furthermore, I get errors all over the place when I put this in, and I have no idea how to fix this. Moreover, what I am trying to do is take the data that is being saved in my UILabel which is a name, and I want that to be shown up in the clickable part of the alert that "dismisses" the alert, but I have no idea how to do that or even get started when I can't add a basic alert into my code. Any help would be great source code even better. Sorry for all the questions. Thanks again in advance.
import UIKit
import MultipeerConnectivity
class ViewController: UIViewController, MCBrowserViewControllerDelegate {
#IBOutlet weak var input: UITextField!
#IBOutlet weak var output: UILabel!
#IBAction func action(_ sender: Any) {
output.text = input.text
UserDefaults.standard.set(input.text, forKey: "MyName")
input.text = ""
}
var currentPlayer:String!
var appDelegate:AppDelegate!
override func viewDidLoad() {
super.viewDidLoad()
appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.MPCHandler.setupPeerWithDisplayName(UIDevice.current.name)
appDelegate.MPCHandler.setupSession()
appDelegate.MPCHandler.advertiseSelf(true)
NotificationCenter.default.addObserver(self, selector: Selector(("peerChangedStateWithNotification:")), name: NSNotification.Name(rawValue: "MPC_DidChangeStateNotification"), object: nil)
NotificationCenter.default.addObserver(self, selector: Selector(("handleReceivedDataWithNotification:")), name: NSNotification.Name(rawValue: "MPC_DidReceiveDataNotification"), object: nil)
}
#IBAction func connect(_ sender: Any) {
if appDelegate.MPCHandler.session != nil{
appDelegate.MPCHandler.setupBrowser()
appDelegate.MPCHandler.browser.delegate = self
self.present(appDelegate.MPCHandler.browser, animated: true, completion: nil)
}
}
func peerChangedStateWithNotification(notification:NSNotification){
let userInfo = NSDictionary(dictionary: notification.userInfo!)
let state = userInfo.object(forKey: "state") as! Int
if state != MCSessionState.connecting.rawValue{
self.navigationItem.title = "Connected"
}
}
func browserViewControllerDidFinish(_ browserViewController: MCBrowserViewController) {
appDelegate.MPCHandler.browser.dismiss(animated: true, completion: nil)
}
func browserViewControllerWasCancelled(_ browserViewController: MCBrowserViewController) {
appDelegate.MPCHandler.browser.dismiss(animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(_ animated: Bool) {
if let x = UserDefaults.standard.object(forKey:"myName") as?
String
{
output.text = x
}
}
}
func viewDidAppear(_animated: Bool) {
createAlert(title: "HI", message: "ARE YOU READY")
}
func createAlert (title: String, message:String)
{
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "HI", style: UIAlertActionStyle.default, handler: { (action) in alert.dismiss(animated: true, completion: nil);))
self.present(alert,animated: true, completion:nil)
}
}
The error you are most probably getting is Invalid redeclaration of 'viewDidAppear' means you are trying to add viewDidAppear method twice in your ViewController. So remove the below one method form your code and call createAlert inside the already exist viewDidAppear one.
Your second mistake is you forgot to add } for UIAlertActionHandler and there is no need to call dismiss on alert action it will automatically dismiss the alert.
You need to also change your selector syntax to Swift3 one and also you forgot to add handleReceivedDataWithNotification with your code.
Now with Swift use Swift native dictionary type instead of NSDictionary, so change your controller with below one to get your desired output.
class ViewController: UIViewController, MCBrowserViewControllerDelegate {
#IBOutlet weak var input: UITextField!
#IBOutlet weak var output: UILabel!
var currentPlayer:String!
var appDelegate:AppDelegate!
override func viewDidLoad() {
super.viewDidLoad()
appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.MPCHandler.setupPeerWithDisplayName(UIDevice.current.name)
appDelegate.MPCHandler.setupSession()
appDelegate.MPCHandler.advertiseSelf(true)
NotificationCenter.default.addObserver(self, selector: #selector(peerChangedStateWithNotification(_:)), name: NSNotification.Name(rawValue: "MPC_DidChangeStateNotification"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleReceivedDataWithNotification(_:)), name: NSNotification.Name(rawValue: "MPC_DidReceiveDataNotification"), object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func connect(_ sender: Any) {
if appDelegate.MPCHandler.session != nil{
appDelegate.MPCHandler.setupBrowser()
appDelegate.MPCHandler.browser.delegate = self
self.present(appDelegate.MPCHandler.browser, animated: true, completion: nil)
}
}
#IBAction func action(_ sender: Any) {
output.text = input.text
UserDefaults.standard.set(input.text, forKey: "MyName")
input.text = ""
}
func peerChangedStateWithNotification(_ notification: Notification) {
let userInfo = notification.userInfo!
let state = userInfo["state"] as! Int
if state != MCSessionState.connecting.rawValue{
self.navigationItem.title = "Connected"
}
}
func handleReceivedDataWithNotification(_ notification: Notification) {
let userInfo = notification.userInfo!
print(userInfo)
}
func browserViewControllerDidFinish(_ browserViewController: MCBrowserViewController) {
appDelegate.MPCHandler.browser.dismiss(animated: true, completion: nil)
}
func browserViewControllerWasCancelled(_ browserViewController: MCBrowserViewController) {
appDelegate.MPCHandler.browser.dismiss(animated: true, completion: nil)
}
override func viewDidAppear(_ animated: Bool) {
if let x = UserDefaults.standard.string(forKey: "myName") {
output.text = x
}
else {
output.text = "Default Name" //Set here default Name
}
self.createAlert(title: "HI", message: "ARE YOU READY")
}
func createAlert (title: String, message:String)
{
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: output.text, style: UIAlertActionStyle.default, handler: { (action) in
}))
self.present(alert,animated: true, completion:nil)
}
}
import UIKit
import MultipeerConnectivity
class ViewController: UIViewController, MCBrowserViewControllerDelegate {
#IBOutlet weak var input: UITextField!
#IBOutlet weak var output: UILabel!
#IBAction func dick(_ sender: Any) {
output.text = input.text
UserDefaults.standard.set(input.text, forKey: "MyName")
input.text = ""
}
var currentPlayer:String!
var appDelegate:AppDelegate!
override func viewDidLoad() {
super.viewDidLoad()
appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.MPCHandler.setupPeerWithDisplayName(UIDevice.current.name)
appDelegate.MPCHandler.setupSession()
appDelegate.MPCHandler.advertiseSelf(true)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.peerChangedStateWithNotification(_:)), name: NSNotification.Name(rawValue: "MPC_DidChangeStateNotification"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.handleReceivedDataWithNotification(_:)), name: NSNotification.Name(rawValue: "MPC_DidReceiveDataNotification"), object: nil)
}
#IBAction func connect(_ sender: Any) {
if appDelegate.MPCHandler.session != nil{
appDelegate.MPCHandler.setupBrowser()
appDelegate.MPCHandler.browser.delegate = self
self.present(appDelegate.MPCHandler.browser, animated: true, completion: nil)
}
}
#IBAction func action(_ sender: Any) {
output.text = input.text
UserDefaults.standard.set(input.text, forKey: "MyName")
input.text = ""
}
func peerChangedStateWithNotification(_ notification: Notification) {
let userInfo = notification.userInfo!
let state = userInfo["state"] as! Int
if state != MCSessionState.connecting.rawValue{
self.navigationItem.title = "Connected"
}
}
func handleReceivedDataWithNotification(_ notification: Notification) {
let userInfo = notification.userInfo!
print(userInfo)
}
func browserViewControllerDidFinish(_ browserViewController: MCBrowserViewController) {
appDelegate.MPCHandler.browser.dismiss(animated: true, completion: nil)
}
func browserViewControllerWasCancelled(_ browserViewController: MCBrowserViewController) {
appDelegate.MPCHandler.browser.dismiss(animated: true, completion: nil)
}
*func viewdidloadOverride; func viewDidAppear*(_ animated: Bool) {
if let x = UserDefaults.standard.string(forKey: "myName") {
output.text = x
}
else {
output.text = "x" //Set here default Name
}
self.createAlert(title: "HI", message: "ARE YOU READY")
}
func createAlert (title: String, message:String)
{
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: output.text, style: UIAlertActionStyle.default, handler: { (action) in
}))
self.present(alert,animated: true, completion:nil)
}
}

MapView in a VC and its Searchbar in another

As per the title, in general I'd like to show, in one VC, a MapView and in a second VC a SearchBar (using another TableVC to display, as the user types, "GeoElements" obtained by MKLocalSearchRequest). This because I want to display in the Map some AnnotationViews with custom Callouts. My problem is that the TableVC doesn't update with placemarks as the user types in the SearchBar..
MAPVIEW code:
import UIKit
import MapKit
protocol HandleMapSearch {
func dropPinZoomIn(placemark:MKPlacemark)
}
class ViewController: UIViewController {
#IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
var selectedPin:MKPlacemark? = nil
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
locationManager.requestWhenInUseAuthorization()
locationManager.requestLocation()
}
func getDirections(){
if let selectedPin = selectedPin {
let mapItem = MKMapItem(placemark: selectedPin)
let launchOptions = [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving]
mapItem.openInMaps(launchOptions: launchOptions)
}
}
}
extension ViewController : CLLocationManagerDelegate {
private func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse {
locationManager.requestLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
let span = MKCoordinateSpanMake(0.05, 0.05)
let region = MKCoordinateRegion(center: location.coordinate, span: span)
mapView.setRegion(region, animated: true)
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("error:: (error)")
}
}
extension ViewController: HandleMapSearch {
func dropPinZoomIn(placemark:MKPlacemark){
// cache the pin
selectedPin = placemark
let annotation = MKPointAnnotation()
annotation.coordinate = placemark.coordinate
annotation.title = placemark.name
if let city = placemark.locality,
let state = placemark.administrativeArea {
annotation.subtitle = "(city) (state)"
}
mapView.addAnnotation(annotation)
let span = MKCoordinateSpanMake(0.05, 0.05)
let region = MKCoordinateRegionMake(placemark.coordinate, span)
mapView.setRegion(region, animated: true)
}
}
extension ViewController : MKMapViewDelegate {
func mapView(_: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?{
if annotation is MKUserLocation {
//return nil so map view draws "blue dot" for standard user location
return nil
}
let reuseId = "pin"
var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView?.pinTintColor = UIColor.orange
pinView?.canShowCallout = true
let smallSquare = CGSize(width: 30, height: 30)
let button = UIButton(frame: CGRect(origin: CGPoint(x: 0,y :0), size: smallSquare))
button.setBackgroundImage(UIImage(named: "car"), for: .normal)
button.addTarget(self, action: Selector(("getDirections")), for: .touchUpInside)
pinView?.leftCalloutAccessoryView = button
return pinView
}
}
EVENT code:
import UIKit
import MapKit
class EventVC: UIViewController {
var resultSearchController:UISearchController? = nil
override func viewDidLoad() {
super.viewDidLoad()
let locationSearchTable = storyboard!.instantiateViewController(withIdentifier: "LocationSearchTable") as! LocationSearchTable
resultSearchController = UISearchController(searchResultsController: locationSearchTable)
resultSearchController?.searchResultsUpdater = locationSearchTable
let searchBar = resultSearchController!.searchBar
searchBar.sizeToFit()
searchBar.placeholder = "Insert Address"
navigationItem.titleView = resultSearchController?.searchBar
resultSearchController?.hidesNavigationBarDuringPresentation = false
resultSearchController?.dimsBackgroundDuringPresentation = true
definesPresentationContext = true
//these two below are problematic
locationSearchTable.mapView = mapView
locationSearchTable.handleMapSearchDelegate = self
}
}
LOCATIONSEARCHTABLE code:
import UIKit
import MapKit
class LocationSearchTable: UITableViewController {
var matchingItems:[MKMapItem] = []
var mapView: MKMapView? = nil
var handleMapSearchDelegate:HandleMapSearch? = nil
override func viewDidLoad() {
super.viewDidLoad()
}
func parseAddress(selectedItem:MKPlacemark) -> String {
// put a space between "4" and "Melrose Place"
let firstSpace = (selectedItem.subThoroughfare != nil && selectedItem.thoroughfare != nil) ? " " : ""
// put a comma between street and city/state
let comma = (selectedItem.subThoroughfare != nil || selectedItem.thoroughfare != nil) && (selectedItem.subAdministrativeArea != nil || selectedItem.administrativeArea != nil) ? ", " : ""
// put a space between "Washington" and "DC"
let secondSpace = (selectedItem.subAdministrativeArea != nil && selectedItem.administrativeArea != nil) ? " " : ""
let addressLine = String(
format:"%#%#%#%#%#%#%#",
// street number
selectedItem.subThoroughfare ?? "",
firstSpace,
// street name
selectedItem.thoroughfare ?? "",
comma,
// city
selectedItem.locality ?? "",
secondSpace,
// state
selectedItem.administrativeArea ?? ""
)
return addressLine
}
}
extension LocationSearchTable : UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController){
guard let mapView = mapView,
let searchBarText = searchController.searchBar.text else { return }
let request = MKLocalSearchRequest()
request.naturalLanguageQuery = searchBarText
request.region = mapView.region
let search = MKLocalSearch(request: request)
search.start { response, _ in
guard let response = response else {
return
}
self.matchingItems = response.mapItems
self.tableView.reloadData()
}
}
}
extension LocationSearchTable {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return matchingItems.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
let selectedItem = matchingItems[indexPath.row].placemark
cell.textLabel?.text = selectedItem.name
cell.detailTextLabel?.text = parseAddress(selectedItem: selectedItem)
return cell
}
}

Error in conversion Swift 2 to Swift 3 MKDirections and MKDirections

I am having difficulties converting two sections of code from Swift 2 to Swift 3
The working Swift 2 Code Block was
func showRoute(routes: [MKRoute], time: NSTimeInterval) {
var directionsArray = [(startingAddress: String, endingAddress: String, route: MKRoute)]()
for i in 0..<routes.count {
plotPolyline(routes[i])
directionsArray += [(locationArray[i].textField.text!,
locationArray[i+1].textField.text!, routes[i])]
}
displayDirections(directionsArray)
printTimeToLabel(time)
}
Swift 3 has converted this to
func showRoute(routes: [MKRoute], time: TimeInterval) {
var directionsArray = [(startingAddress: String, endingAddress: String, route: MKRoute)]()
for i in 0..<routes.count {
plotPolyline(route: routes[i])
directionsArray += [(locationArray[i].textField?.text,
locationArray[i+1].textField?.text, routes[i])]
}
displayDirections(directionsArray: directionsArray)
printTimeToLabel(time: time)
}
This produces an error on the line
directionsArray += [(locationArray[i].textField?.text,
locationArray[i+1].textField?.text, routes[i])]
Cannot convert value of type '[(startingAddress: String, endingAddress: String, route: MKRoute)]' to expected argument type 'inout _'
If anyone can help i would really appreciate it
Just need
directionsArray += [(startingAddress : locationArray[i].textField!.text!,
endingAddress : locationArray[i+1].textField!.text!,
route : routes[i])]
I saw your question, but There are no answers. And, That is not only one problem.
Here is full body of ViewController:
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController {
#IBOutlet weak var sourceField: UITextField!
#IBOutlet weak var destinationField1: UITextField!
#IBOutlet weak var destinationField2: UITextField!
#IBOutlet weak var topMarginConstraint: NSLayoutConstraint!
#IBOutlet var enterButtonArray: [UIButton]!
var originalTopMargin: CGFloat!
let locationManager = CLLocationManager()
var locationTuples: [(textField: UITextField?, mapItem: MKMapItem?)]!
var locationsArray: [(textField: UITextField?, mapItem: MKMapItem?)] {
var filtered = locationTuples.filter({ $0.mapItem != nil })
filtered += [filtered.first!]
return filtered
}
override func viewDidLoad() {
super.viewDidLoad()
originalTopMargin = topMarginConstraint.constant
locationTuples = [(sourceField, nil), (destinationField1, nil), (destinationField2, nil)]
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.requestLocation()
}
}
override func viewWillAppear(_ animated: Bool) {
navigationController?.isNavigationBarHidden = true
}
#IBAction func getDirections(_ sender: AnyObject) {
view.endEditing(true)
performSegue(withIdentifier: "show_directions", sender: self)
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
if locationTuples[0].mapItem == nil ||
(locationTuples[1].mapItem == nil && locationTuples[2].mapItem == nil) {
showAlert("Please enter a valid starting point and at least one destination.")
return false
} else {
return true
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let directionsViewController = segue.destination as! DirectionsViewController
directionsViewController.locationArray = locationsArray
}
#IBAction func addressEntered(_ sender: UIButton) {
view.endEditing(true)
let currentTextField = locationTuples[sender.tag-1].textField
CLGeocoder().geocodeAddressString(currentTextField!.text!,
completionHandler: {(placemarks, error) -> Void in
if let placemarks = placemarks {
var addresses = [String]()
for placemark in placemarks {
addresses.append(self.formatAddressFromPlacemark(placemark))
}
self.showAddressTable(addresses, textField:currentTextField!,
placemarks:placemarks, sender:sender)
} else {
self.showAlert("Address not found.")
}
} )
}
func showAddressTable(_ addresses: [String], textField: UITextField,
placemarks: [CLPlacemark], sender: UIButton) {
let addressTableView = AddressTableView(frame: UIScreen.main.bounds, style: UITableViewStyle.plain)
addressTableView.addresses = addresses
addressTableView.currentTextField = textField
addressTableView.placemarkArray = placemarks
addressTableView.mainViewController = self
addressTableView.sender = sender
addressTableView.delegate = addressTableView
addressTableView.dataSource = addressTableView
view.addSubview(addressTableView)
}
func formatAddressFromPlacemark(_ placemark: CLPlacemark) -> String {
return (placemark.addressDictionary!["FormattedAddressLines"] as! [String]).joined(separator: ", ")
}
#IBAction func swapFields(_ sender: AnyObject) {
swap(&destinationField1.text, &destinationField2.text)
swap(&locationTuples[1].mapItem, &locationTuples[2].mapItem)
swap(&self.enterButtonArray.filter{$0.tag == 2}.first!.isSelected, &self.enterButtonArray.filter{$0.tag == 3}.first!.isSelected)
}
func showAlert(_ alertString: String) {
let alert = UIAlertController(title: nil, message: alertString, preferredStyle: .alert)
let okButton = UIAlertAction(title: "OK",
style: .cancel) { (alert) -> Void in
}
alert.addAction(okButton)
present(alert, animated: true, completion: nil)
}
// The remaining methods handle the keyboard resignation/
// move the view so that the first responders aren't hidden
func moveViewUp() {
if topMarginConstraint.constant != originalTopMargin {
return
}
topMarginConstraint.constant -= 165
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.view.layoutIfNeeded()
})
}
func moveViewDown() {
if topMarginConstraint.constant == originalTopMargin {
return
}
topMarginConstraint.constant = originalTopMargin
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.view.layoutIfNeeded()
})
}
}
extension ViewController: UITextFieldDelegate {
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
enterButtonArray.filter{$0.tag == textField.tag}.first!.isSelected = false
locationTuples[textField.tag-1].mapItem = nil
return true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
moveViewUp()
}
func textFieldDidEndEditing(_ textField: UITextField) {
moveViewDown()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
view.endEditing(true)
moveViewDown()
return true
}
}
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
CLGeocoder().reverseGeocodeLocation(locations.last!,
completionHandler: {(placemarks, error) -> Void in
if let placemarks = placemarks {
let placemark = placemarks[0]
self.locationTuples[0].mapItem = MKMapItem(placemark:
MKPlacemark(coordinate: placemark.location!.coordinate,
addressDictionary: placemark.addressDictionary as! [String:AnyObject]?))
self.sourceField.text = self.formatAddressFromPlacemark(placemark)
self.enterButtonArray.filter{$0.tag == 1}.first!.isSelected = true
}
})
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
}
}