I installed pod file Siren in swift 4.2 .But Siren has no member wail error occur! How to fix this solution? - swift4.2

I am working in Swift4.2 and import siren in my project .BUt error occur.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
UINavigationBar.appearance().barTintColor = UIColor(red: 0/255.0, green: 85/255.0, blue: 127/255.0, alpha: 1)
UINavigationBar.appearance().tintColor = UIColor.white
// UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white,NSAttributedString.Key.font: UIFont(name: "Roboto-Medium", size: 16)!]
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffset(horizontal: 0, vertical: -60), for:UIBarMetrics.default)
UINavigationBar.appearance().isTranslucent = false
UIApplication.shared.statusBarStyle = .lightContent
IQKeyboardManager .shared().isEnabled = true
IQKeyboardManager .shared().shouldResignOnTouchOutside = true
IQKeyboardManager .shared().isEnableAutoToolbar = false
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
let mainview = UIStoryboard(name:"Main", bundle: nil).instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
let nav = UINavigationController.init(rootViewController: mainview)
SideMenu = LGSideMenuController.init(rootViewController: nav)
SideMenuView = UIStoryboard(name:"Main", bundle: nil).instantiateViewController(withIdentifier: "SideMenuViewController") as! SideMenuViewController
SideMenu.rightViewStatusBarVisibleOptions = .onAll
let rect = SideMenuView.view.frame;
SideMenuView.view.frame = rect
Messaging.messaging().delegate = self
//Setup siren
Siren.shared.wail()
}
return true
}

Related

Image annotation different

I created a map view with different annotation and a search. I can not attribute a different image according to the pin. I also have another concern, when I do a search it removes a pin to put it on the new place sought. Below is the code of a young coder. In advance thank you for your help.
import MapKit
import UIKit
import CoreLocation
class MapViewController: UIViewController, UISearchBarDelegate, MKMapViewDelegate {
#IBOutlet weak var MapView: MKMapView!
var searchController:UISearchController!
var annotation:MKAnnotation!
var localSearchRequest:MKLocalSearchRequest!
var localSearch:MKLocalSearch!
var localSearchResponse:MKLocalSearchResponse!
var error:NSError!
var pointAnnotation:MKPointAnnotation!
var pinAnnotationView:MKPinAnnotationView!
var coordinates: [[Double]]!
var name:[String]!
let regionRadius: CLLocationDistance = 1000
#IBAction func showSearchBar(_ sender: Any) {
searchController = UISearchController(searchResultsController: nil)
searchController.hidesNavigationBarDuringPresentation = false
self.searchController.searchBar.delegate = self
present(searchController, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.MapView.delegate = self
var Tirta = CustomPointAnnotation()
Tirta.coordinate = CLLocationCoordinate2DMake(-8.415162, 115.315360)
Tirta.title = "Tirta Empul"
Tirta.imageName = "PaConseil.png"
var Goa = CustomPointAnnotation()
Goa.coordinate = CLLocationCoordinate2DMake(-8.551313, 115.468865)
Goa.title = "Goa Lawah"
Goa.imageName = "PaMecontent.png"
MapView.addAnnotation(Tirta)
MapView.addAnnotation(Goa)
// 3
let region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: -8.670458199999999, longitude: 115.2126293), span: MKCoordinateSpan(latitudeDelta: 2, longitudeDelta: 2))
self.MapView.setRegion(region, animated: true)
}
func MapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
print("delegate called")
if !(annotation is CustomPointAnnotation) {
return nil
}
let reuseId = "test"
var AnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId)
if AnnotationView == nil {
AnnotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
AnnotationView?.canShowCallout = true
}
else {
AnnotationView?.annotation = annotation
}
func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
let CustomPointAnnotation = annotation as! CustomPointAnnotation
AnnotationView?.image = UIImage(named:CustomPointAnnotation.imageName)
return AnnotationView
}
class CustomPointAnnotation: MKPointAnnotation {
var imageName: String!
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar){
//1
searchBar.resignFirstResponder()
dismiss(animated: true, completion: nil)
if self.MapView.annotations.count != 0{
annotation = self.MapView.annotations[0]
self.MapView.removeAnnotation(annotation)
}
//2
localSearchRequest = MKLocalSearchRequest()
localSearchRequest.naturalLanguageQuery = searchBar.text
localSearch = MKLocalSearch(request: localSearchRequest)
localSearch.start { (localSearchResponse, error) -> Void in
if localSearchResponse == nil{
let alertController = UIAlertController(title: nil, message: "Place Not Found", preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: nil))
self.present(alertController, animated: true, completion: nil)
return
}
//3
self.pointAnnotation = MKPointAnnotation()
self.pointAnnotation.title = searchBar.text
self.pointAnnotation.coordinate = CLLocationCoordinate2D(latitude: localSearchResponse!.boundingRegion.center.latitude, longitude: localSearchResponse!.boundingRegion.center.longitude)
self.pinAnnotationView = MKPinAnnotationView(annotation: self.pointAnnotation, reuseIdentifier: nil)
self.MapView.centerCoordinate = self.pointAnnotation.coordinate
self.MapView.addAnnotation(self.pinAnnotationView.annotation!)
}
}
}
import Foundation
import MapKit
class CustomPointAnnotation: MKPointAnnotation {
var coordinates: CLLocationCoordinate2D
var name: String!
var imageName: UIImage!
init(coordinates: CLLocationCoordinate2D) {
self.coordinates = coordinates
}
}
I'm going to assume that you've updated Xcode so that you are now using Swift 3. Well then, the problem is that this method is never being executed:
func MapView(mapView: MKMapView!,
viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
... and the reason is that that is not its correct "signature". That method is now defined like this:
func mapView(_ mapView: MKMapView,
viewFor annotation: MKAnnotation) -> MKAnnotationView?

Resize image from internet

My app retrieves an image from URL, but I need to change the image size before it appears on the user interface in my tableview.
Here is my tableViewController code:
import UIKit
import Firebase
import Alamofire
class FeedViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var postField: MaterialTextField!
#IBOutlet weak var imageSelectorImage: UIImageView!
var posts = [Post]()
var imageSelected = false
var imagePicker: UIImagePickerController!
static var imageCache = NSCache()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
postField.delegate = self
//tableView.estimatedRowHeight = 400
//tableView.rowHeight = UITableViewAutomaticDimension
imagePicker = UIImagePickerController()
imagePicker.delegate = self
DataService.ds.REF_POSTS.queryOrderedByChild("timestamp").observeEventType(.Value, withBlock: { snapshot in
self.posts = []
if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] {
for snap in snapshots {
if let postDict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let post = Post(postKey: key, dictionary: postDict)
self.posts.insert(post, atIndex: 0)
}
}
}
self.tableView.reloadData()
})
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
/**
* Called when the user click on the view (outside the UITextField).
*/
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldDidBeginEditing(textField: UITextField) {
animateViewMoving(true, moveValue: 167)
}
func textFieldDidEndEditing(textField: UITextField) {
animateViewMoving(false, moveValue: 167)
}
func animateViewMoving (up:Bool, moveValue :CGFloat){
let movementDuration:NSTimeInterval = 0.1
let movement:CGFloat = ( up ? -moveValue : moveValue)
UIView.beginAnimations( "animateView", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(movementDuration )
self.view.frame = CGRectOffset(self.view.frame, 0, movement)
UIView.commitAnimations()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let post = posts[indexPath.row]
print(post.postDescription)
if let cell = tableView.dequeueReusableCellWithIdentifier("PostCell") as? PostCell {
cell.request?.cancel()
var img: UIImage?
if let url = post.imageUrl {
img = FeedViewController.imageCache.objectForKey(url) as? UIImage
}
cell.configureCell(post, img: img)
return cell
} else {
return PostCell()
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
imagePicker.dismissViewControllerAnimated(true, completion: nil)
imageSelectorImage.image = image
imageSelected = true
}
#IBAction func selectImage(sender: UITapGestureRecognizer) {
presentViewController(imagePicker, animated: true, completion: nil)
}
#IBAction func makePost(sender: AnyObject) {
//TODO: Add loading spinner while data is being processed
if let txt = postField.text where txt != "" {
if let img = imageSelectorImage.image where imageSelected == true {
let urlStr = URL_IMGSHACK
let url = NSURL(string: urlStr)!
//FIXME: Add error handling
let imgData = UIImageJPEGRepresentation(img, 0.2)!
let keyData = API_KEY_IMG.dataUsingEncoding(NSUTF8StringEncoding)!
let keyJSON = "json".dataUsingEncoding(NSUTF8StringEncoding)!
Alamofire.upload(.POST, url, multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: imgData, name: "fileupload", fileName: "image",
mimeType: "image/jpg")
multipartFormData.appendBodyPart(data: keyData, name: "key")
multipartFormData.appendBodyPart(data: keyJSON, name: "format")
}) { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON(completionHandler: { response in
if let info = response.result.value as? Dictionary<String, AnyObject> {
if let links = info["links"] as? Dictionary<String, AnyObject>{
if let imgLink = links["image_link"] as? String {
print("LINK: \(imgLink)")
self.postToFirebase(imgLink)
}
}
}
})
case .Failure(let error):
print(error)
}
}
} else {
self.postToFirebase(nil)
}
}
}
func postToFirebase(imgUrl: String?) {
var post: Dictionary<String, AnyObject> = [
"timestamp": NSNumber(longLong: currentTimeMillis()),
"description": postField.text!,
"likes": 0
]
if imgUrl != nil {
post["imageUrl"] = imgUrl!
}
let firebasePost = DataService.ds.REF_POSTS.childByAutoId()
firebasePost.setValue(post)
postField.text = ""
imageSelectorImage.image = UIImage(named: "camera")
imageSelected = false
tableView.reloadData()
postField.resignFirstResponder()
}
func currentTimeMillis() ->Int64 {
let nowDouble = NSDate().timeIntervalSince1970
return Int64(nowDouble * 1000)
}
}
and here is my custom cell:
class PostCell: UITableViewCell {
#IBOutlet weak var profileImage: UIImageView!
#IBOutlet weak var showcaseImage: UIImageView!
#IBOutlet weak var descriptionText: UILabel!
#IBOutlet weak var likesLabel: UILabel!
#IBOutlet weak var likeImage: UIImageView!
var post: Post!
var request: Request?
var likeRef: Firebase!
override func awakeFromNib() {
super.awakeFromNib()
let tap = UITapGestureRecognizer(target: self, action: "likeTapped:")
tap.numberOfTapsRequired = 1
likeImage.addGestureRecognizer(tap)
likeImage.userInteractionEnabled = true
}
override func drawRect(rect: CGRect) {
profileImage.layer.cornerRadius = self.profileImage.frame.size.width / 2
profileImage.backgroundColor = UIColor.clearColor()
profileImage.layer.borderWidth = 2
profileImage.layer.borderColor = UIColor.whiteColor().CGColor
self.profileImage.clipsToBounds = true
self.showcaseImage.clipsToBounds = true
}
func configureCell(post: Post, img: UIImage?){
self.post = post
likeRef = DataService.ds.REF_USERS_CURRENT.childByAppendingPath("likes").childByAppendingPath(post.postKey)
self.descriptionText.text = post.postDescription
self.likesLabel.text = "\(post.likes)"
if post.imageUrl != nil {
if img != nil {
self.showcaseImage.image = img
} else {
request = Alamofire.request(.GET, post.imageUrl!).validate(contentType: ["image/*"]).response(completionHandler: { request, response, data, err in
if err == nil {
let img = UIImage(data: data!)!
self.showcaseImage.image = img
FeedViewController.imageCache.setObject(img, forKey: self.post.imageUrl!)
} else {
print(err.debugDescription)
}
})
}
} else {
self.showcaseImage.hidden = true
}
likeRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
if let doesNotExist = snapshot.value as?
NSNull {
//This mean we have not liked this specific post
self.likeImage.image = UIImage(named: "heart-empty")
} else {
self.likeImage.image = UIImage(named: "heart-full")
}
})
}
func likeTapped(sender: UITapGestureRecognizer) {
likeRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
if let doesNotExist = snapshot.value as?
NSNull {
self.likeImage.image = UIImage(named: "heart-full")
self.post.adjustLikes(true)
self.likeRef.setValue(true)
} else {
self.likeImage.image = UIImage(named: "heart-empty")
self.post.adjustLikes(false)
self.likeRef.removeValue()
}
})
}
}
Here is an example showing what I want to achieve:
this when user post the portrait image
this when user post the landscape image
In summary, I want the image width to fit the width of the device screen, and the height of the uiimage to be dynamic, regardless of the image orientation (landscape or portrait).
Try this part, where 300x600 is needed size of your image to save.
let image = UIImage(data: data!)
UIGraphicsBeginImageContext(CGSizeMake(300, 600))
image?.drawInRect(CGRectMake(0, 0, 300, 600))
let smallImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

need help about resize image swift 2

My app retrieves image from URL, but I need to change the image size before it appears on the user interface in my tableview.
this is my code in my tableViewController:
import UIKit
import Firebase
import Alamofire
class FeedViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var postField: MaterialTextField!
#IBOutlet weak var imageSelectorImage: UIImageView!
var posts = [Post]()
var imageSelected = false
var imagePicker: UIImagePickerController!
static var imageCache = NSCache()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
postField.delegate = self
//tableView.estimatedRowHeight = 400
//tableView.rowHeight = UITableViewAutomaticDimension
imagePicker = UIImagePickerController()
imagePicker.delegate = self
DataService.ds.REF_POSTS.queryOrderedByChild("timestamp").observeEventType(.Value, withBlock: { snapshot in
self.posts = []
if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] {
for snap in snapshots {
if let postDict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let post = Post(postKey: key, dictionary: postDict)
self.posts.insert(post, atIndex: 0)
}
}
}
self.tableView.reloadData()
})
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
/**
* Called when the user click on the view (outside the UITextField).
*/
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldDidBeginEditing(textField: UITextField) {
animateViewMoving(true, moveValue: 167)
}
func textFieldDidEndEditing(textField: UITextField) {
animateViewMoving(false, moveValue: 167)
}
func animateViewMoving (up:Bool, moveValue :CGFloat){
let movementDuration:NSTimeInterval = 0.1
let movement:CGFloat = ( up ? -moveValue : moveValue)
UIView.beginAnimations( "animateView", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(movementDuration )
self.view.frame = CGRectOffset(self.view.frame, 0, movement)
UIView.commitAnimations()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let post = posts[indexPath.row]
print(post.postDescription)
if let cell = tableView.dequeueReusableCellWithIdentifier("PostCell") as? PostCell {
cell.request?.cancel()
var img: UIImage?
if let url = post.imageUrl {
img = FeedViewController.imageCache.objectForKey(url) as? UIImage
}
cell.configureCell(post, img: img)
return cell
} else {
return PostCell()
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
imagePicker.dismissViewControllerAnimated(true, completion: nil)
imageSelectorImage.image = image
imageSelected = true
}
#IBAction func selectImage(sender: UITapGestureRecognizer) {
presentViewController(imagePicker, animated: true, completion: nil)
}
#IBAction func makePost(sender: AnyObject) {
//TODO: Add loading spinner while data is being processed
if let txt = postField.text where txt != "" {
if let img = imageSelectorImage.image where imageSelected == true {
let urlStr = URL_IMGSHACK
let url = NSURL(string: urlStr)!
//FIXME: Add error handling
let imgData = UIImageJPEGRepresentation(img, 0.2)!
let keyData = API_KEY_IMG.dataUsingEncoding(NSUTF8StringEncoding)!
let keyJSON = "json".dataUsingEncoding(NSUTF8StringEncoding)!
Alamofire.upload(.POST, url, multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: imgData, name: "fileupload", fileName: "image",
mimeType: "image/jpg")
multipartFormData.appendBodyPart(data: keyData, name: "key")
multipartFormData.appendBodyPart(data: keyJSON, name: "format")
}) { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON(completionHandler: { response in
if let info = response.result.value as? Dictionary<String, AnyObject> {
if let links = info["links"] as? Dictionary<String, AnyObject>{
if let imgLink = links["image_link"] as? String {
print("LINK: \(imgLink)")
self.postToFirebase(imgLink)
}
}
}
})
case .Failure(let error):
print(error)
}
}
} else {
self.postToFirebase(nil)
}
}
}
func postToFirebase(imgUrl: String?) {
var post: Dictionary<String, AnyObject> = [
"timestamp": NSNumber(longLong: currentTimeMillis()),
"description": postField.text!,
"likes": 0
]
if imgUrl != nil {
post["imageUrl"] = imgUrl!
}
let firebasePost = DataService.ds.REF_POSTS.childByAutoId()
firebasePost.setValue(post)
postField.text = ""
imageSelectorImage.image = UIImage(named: "camera")
imageSelected = false
tableView.reloadData()
postField.resignFirstResponder()
}
func currentTimeMillis() ->Int64 {
let nowDouble = NSDate().timeIntervalSince1970
return Int64(nowDouble * 1000)
}
}
and here my custom cell:
class PostCell: UITableViewCell {
#IBOutlet weak var profileImage: UIImageView!
#IBOutlet weak var showcaseImage: UIImageView!
#IBOutlet weak var descriptionText: UILabel!
#IBOutlet weak var likesLabel: UILabel!
#IBOutlet weak var likeImage: UIImageView!
var post: Post!
var request: Request?
var likeRef: Firebase!
override func awakeFromNib() {
super.awakeFromNib()
let tap = UITapGestureRecognizer(target: self, action: "likeTapped:")
tap.numberOfTapsRequired = 1
likeImage.addGestureRecognizer(tap)
likeImage.userInteractionEnabled = true
}
override func drawRect(rect: CGRect) {
profileImage.layer.cornerRadius = self.profileImage.frame.size.width / 2
profileImage.backgroundColor = UIColor.clearColor()
profileImage.layer.borderWidth = 2
profileImage.layer.borderColor = UIColor.whiteColor().CGColor
self.profileImage.clipsToBounds = true
self.showcaseImage.clipsToBounds = true
}
func configureCell(post: Post, img: UIImage?){
self.post = post
likeRef = DataService.ds.REF_USERS_CURRENT.childByAppendingPath("likes").childByAppendingPath(post.postKey)
self.descriptionText.text = post.postDescription
self.likesLabel.text = "\(post.likes)"
if post.imageUrl != nil {
if img != nil {
self.showcaseImage.image = img
} else {
request = Alamofire.request(.GET, post.imageUrl!).validate(contentType: ["image/*"]).response(completionHandler: { request, response, data, err in
if err == nil {
let img = UIImage(data: data!)!
self.showcaseImage.image = img
FeedViewController.imageCache.setObject(img, forKey: self.post.imageUrl!)
} else {
print(err.debugDescription)
}
})
}
} else {
self.showcaseImage.hidden = true
}
likeRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
if let doesNotExist = snapshot.value as?
NSNull {
//This mean we have not liked this specific post
self.likeImage.image = UIImage(named: "heart-empty")
} else {
self.likeImage.image = UIImage(named: "heart-full")
}
})
}
func likeTapped(sender: UITapGestureRecognizer) {
likeRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
if let doesNotExist = snapshot.value as?
NSNull {
self.likeImage.image = UIImage(named: "heart-full")
self.post.adjustLikes(true)
self.likeRef.setValue(true)
} else {
self.likeImage.image = UIImage(named: "heart-empty")
self.post.adjustLikes(false)
self.likeRef.removeValue()
}
})
}
}
this example for what i want to achieve:
this when user post the portrait image
this when user post the landscape image
The point is that I want my image width to always fit the width of device screen, and the height of the uiimage will be dynamic.
so when user post any image with any orientation ( landscape or portrait ), the image will fit the width of the screen, the height will be dynamic.
please help me give the detail where to put your method since i am a newbie about this, how to achieve what i want... im so desperated, is already 1 month and im so stuck about this...
You need to add imageview to storyboard from interface builder in Xcode,then you can set its constraints to fit size of the screen,& also add height constraints which you can change later when you retrieve image from url

How can i make my own view and pop it up ? i want to make a language picker when taped on button click alert which contain 7 languages

I want to input in it a 7 languages that the user pick then click OK or Cancel to set it on a label. Sorry for asking a lot but I couldn't find any good answers. All I found was about datepicker i want to do the same page this guy using (Showing a UIPickerView with UIActionSheet in iOS8 not working) can u help me plz with any info thanks in advance
That is the code I used to solve my problem plus the autocomplete for anyone having the same problem as me.
Here is the solution for datepicker with (done,cancel) buttons
var picker = UIPickerView()
var autocompleteUrls = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// The Auto Compelete Delegates
DatePickerTextOutLet.delegate = self
NationalityOutLet.delegate = self
AutoComTable.delegate = self
AutoComTable.dataSource = self
AutoComTable.scrollEnabled = true
AutoComTable.hidden = true
} // ViewdidLoad
///////////////////////////////////Language picker
func PickerSensei(textField:UITextField){
let picker: UIPickerView
picker = UIPickerView(frame: CGRectMake(0, 200, view.frame.width, 200))
picker.backgroundColor = .whiteColor()
picker.showsSelectionIndicator = true
picker.delegate = self
picker.dataSource = self
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.Default
toolBar.translucent = true
toolBar.tintColor = UIColor(red: 226/255, green: 0/255, blue: 0/255, alpha: 1)
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "donePicker")
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
// let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "CancelPicker")
toolBar.setItems([ spaceButton, doneButton], animated: false)
toolBar.userInteractionEnabled = true
textField.inputView = picker
textField.inputAccessoryView = toolBar
}
func donePicker() {
PickerSensei(FirstnameoutLet)
if ((FirstnameoutLet.text?.characters.count) < 1 ){
FirstnameoutLet.text = "Arabic"
}
FirstnameoutLet.resignFirstResponder()
}
func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let attributedString = NSAttributedString(string: PreferedLanguagesResult[row], attributes: [NSForegroundColorAttributeName : UIColor.redColor()])
return attributedString
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{
return 1
}
// returns the # of rows in each component..
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
return PreferedLanguagesResult.count
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
FirstnameoutLet.text = String(PreferedLanguagesResult[row])
// FirstnameoutLet.endEditing(true)
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return self.PreferedLanguagesResult[row]
}
//////////////////////// end of Langauge picker
//////// Date Picker
#IBAction func DatePickeractionButton(sender: AnyObject) {
}
func textFieldDidBeginEditing(textField: UITextField) {
datePicker.datePickerMode = UIDatePickerMode.Date
DatePickerTextOutLet.inputView = datePicker
// datePicker.addTarget(self, action: "datePickerChanged:", forControlEvents: .ValueChanged)
BirthDate = DatePickerTextOutLet.text!
let toolBar = UIToolbar()
toolBar.barStyle = .Default
toolBar.translucent = true
toolBar.tintColor = UIColor(red: 216/255, green: 0/255, blue: 0/255, alpha: 1)
toolBar.sizeToFit()
datePicker.setValue(UIColor.redColor(), forKeyPath: "textColor")
datePicker.backgroundColor = UIColor.whiteColor()
// Adds the buttons
let doneButton = UIBarButtonItem(title: "Done", style: .Plain, target: self, action: "doneClick")
let spaceButton = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: "cancelClick")
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.userInteractionEnabled = true
// Adds the toolbar to the view
DatePickerTextOutLet.inputView = datePicker
DatePickerTextOutLet.inputAccessoryView = toolBar
// print(BirthDate)
}
func doneClick() {
print(datePicker.date.age)
if ((datePicker.date.age) >= 9460800 && (datePicker.date.age) <= 42048000 ){
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .ShortStyle
dateFormatter.dateFormat = "dd/MM/yyyy"
DatePickerTextOutLet.text = dateFormatter.stringFromDate(datePicker.date)
DatePickerTextOutLet.resignFirstResponder()
}
else if ((datePicker.date.age) <= 9460800 ){
alertWithTitle("Go Home", message: "You are To young my Child", ViewController: self, toFocus: DatePickerTextOutLet)
} //younger than 18 Years Old
else if ((datePicker.date.age) >= 42048000 ){
alertWithTitle("Sorry Sir", message: "You are to Old for This Shit", ViewController: self, toFocus: DatePickerTextOutLet)
}// older than 80 Years Old
}
func cancelClick() {
DatePickerTextOutLet.resignFirstResponder()
}
///////// Date Picker End
/////////////////// that as for the picker now for the auto complete :-
//////////////////////// The Begining of Auto Compelete
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
AutoComTable!.hidden = false
let text = NationalityOutLet.text ?? ""
let substring = ( text as NSString ).stringByReplacingCharactersInRange(range, withString: string )
searchAutocompleteEntriesWithSubstring(substring)
return true
}
func searchAutocompleteEntriesWithSubstring(substring: String)
{
autocompleteUrls.removeAll(keepCapacity: false)
// print(substring)
for curString in NationalityIDResults
{
// print(curString)
let myString: NSString! = curString as! NSString
let substringRange: NSRange! = myString.rangeOfString(substring)
if (substringRange.location == 0)
{
autocompleteUrls.append(String(curString))
}
}
AutoComTable.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return autocompleteUrls.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let autoCompleteRowIdentifier = "AutoCompleteRowIdentifier"
var cell = tableView.dequeueReusableCellWithIdentifier(autoCompleteRowIdentifier) as UITableViewCell!
// print(cell)
if let tempo1 = cell
{
let index = indexPath.row as Int
cell.textLabel!.text = autocompleteUrls[index]
} else
{
cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: autoCompleteRowIdentifier)
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedCell : UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!
// var currentTextField = textField.text
NationalityOutLet.text = selectedCell.textLabel!.text
AutoComTable.hidden = true
}
////////////////////////////////////////// The End of Auto Compelete

Terminator found in the middle of a basic block

All went fine until my project won't compile.I see those things on two of my files.
Terminator found in the middle of a basic block!
label %50
LLVM ERROR: Broken function found, compilation aborted!
Terminator found in the middle of a basic block!
label %71
LLVM ERROR: Broken function found, compilation aborted!
And the error the compiler give
Command /Applications/Xcode-beta 2.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1
I tried solving it, but no success.
Older version of the files compile.
The problem is in the files,but what is the terminator?
Where is the problem?
EDIT
Here is some code, the classes are big
LandscapeViewController
import UIKit
class LandscapeViewController: UIViewController,UIScrollViewDelegate {
// MARK: Properties
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var pageControl: UIPageControl!
var search: Search!
private var firstTime = true
private var downloadTasks = [NSURLSessionDownloadTask]()
#IBAction func pageChange(sender: UIPageControl){
UIView.animateWithDuration(0.3, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
self.scrollView.contentOffset = CGPoint(x: self.scrollView.bounds.size.width * CGFloat(sender.currentPage), y: 0)
}, completion: nil )
}
// MARK: Buttons
private func tileButtons(searchResults: [SearchResult]){
var columnsPerPage = 5
var rowsPerPage = 3
var itemWidth: CGFloat = 96
var itemHeight: CGFloat = 88
var marginX: CGFloat = 0
var marginY: CGFloat = 20
let buttonWidth: CGFloat = 82
let buttonHeight: CGFloat = 82
let scrollViewWidth = scrollView.bounds.size.width
switch scrollViewWidth{
case 568:
columnsPerPage = 6
itemWidth = 94
marginX = 2
case 667:
columnsPerPage = 7
itemWidth = 95
itemHeight = 98
marginX = 1
marginY = 29
case 736:
columnsPerPage = 8
rowsPerPage = 4
itemWidth = 92
default:
break
}
let paddingHorz = (itemWidth - buttonWidth)/2
let paddingVert = (itemHeight - buttonHeight)/2
var row = 0
var column = 0
var x = marginX
for (index,searchResult) in searchResults.enumerate(){
let button = UIButton(type: .Custom)
button.setBackgroundImage(UIImage(named: "LandscapeButton"), forState: .Normal)
downloadImageForSearchResult(searchResult, andPlaceOnButton: button)
button.tag = 2000 + index
button.addTarget(self, action: Selector("buttonPressed:"), forControlEvents: .TouchUpInside)
button.backgroundColor = UIColor.whiteColor()
button.frame = CGRect(x: x + paddingHorz, y: marginY + CGFloat(row)*itemHeight + paddingVert, width: buttonWidth, height: buttonHeight)
scrollView.addSubview(button)
++row
if row == rowsPerPage{
row = 0
++column
x += itemWidth
if column == columnsPerPage{
column = 0
x += marginX * 2
}
}
}
let buttonsPerPage = columnsPerPage * rowsPerPage
let numPages = 1 + (searchResults.count - 1) / buttonsPerPage
pageControl.numberOfPages = numPages
pageControl.currentPage = 0
scrollView.contentSize = CGSize(width: CGFloat(numPages) * scrollViewWidth, height: scrollView.bounds.size.height)
}
private func downloadImageForSearchResult(searchResult: SearchResult,andPlaceOnButton button: UIButton){
if let url = NSURL(string: searchResult.artworkURL60){
let session = NSURLSession.sharedSession()
let downloadTask = session.downloadTaskWithURL(url,completionHandler: { [weak button] url, response, error in
if error == nil && url != nil{
if let data = NSData(contentsOfURL: url!){
if let image = UIImage(data: data){
let resizedImage = image.resizedImageWithBounds(CGSize(width: 60, height: 60))
dispatch_async(dispatch_get_main_queue()){
if let button = button{
button.setImage(resizedImage, forState: .Normal)
}
}
}
}
}
})
downloadTasks.append(downloadTask!)
downloadTask?.resume()
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowDetail"{
switch search.state{
case .Results(let list):
let destinationViewController = segue.destinationViewController as! DetailViewController
let searchResult = list[sender!.tag - 2000]
destinationViewController.searchResult = searchResult
default:
break
}
}
}
func buttonPressed(sender: UIButton){
performSegueWithIdentifier("ShowDetail", sender: sender)
}
// MARK: UIScrollViewDelegate
func scrollViewDidScroll(scrollView: UIScrollView) {
let width = scrollView.bounds.size.width
let currentPage = Int((scrollView.contentOffset.x + width/2) / width)
pageControl.currentPage = currentPage
}
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
pageControl.numberOfPages = 0
scrollView.backgroundColor = UIColor(patternImage: UIImage(named: "LandscapeBackground")!)
view.removeConstraints(view.constraints)
view.translatesAutoresizingMaskIntoConstraints = true
pageControl.removeConstraints(pageControl.constraints)
pageControl.translatesAutoresizingMaskIntoConstraints = true
scrollView.removeConstraints(scrollView.constraints)
scrollView.translatesAutoresizingMaskIntoConstraints = true
// Do any additional setup after loading the view.
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
scrollView.frame = view.bounds
pageControl.frame = CGRect(x: 0, y: view.frame.size.height - pageControl.frame.size.height, width: view.frame.size.width, height: pageControl.frame.size.height)
if firstTime{
firstTime = false
switch search.state{
case .NotSearchedYet:
break
case .Loading:
showSpinner()
case .NoResults:
showNothingFoundLabel()
case.Results(let list):
tileButtons(list)
}
}
}
private func showNothingFoundLabel() {
let label = UILabel(frame: CGRect.zeroRect)
label.text = "Nothing Found"
label.backgroundColor = UIColor.clearColor()
label.textColor = UIColor.whiteColor()
label.sizeToFit()
var rect = label.frame
rect.size.width = ceil(rect.size.width/2) * 2
rect.size.height = ceil(rect.size.height/2) * 2
label.frame = rect
label.center = CGPoint(x: CGRectGetMidX(scrollView.bounds), y: CGRectGetMidY(scrollView.bounds))
view.addSubview(label)
}
private func showSpinner(){
let spinner = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
spinner.center = CGPoint(x: CGRectGetMidX(scrollView.bounds) + 0.5, y: CGRectGetMidY(scrollView.bounds) + 0.5)
spinner.tag = 1000
view.addSubview(spinner)
spinner.startAnimating()
}
func searchResultsRecived(){
hideSpinner()
switch search.state {
case .NotSearchedYet, .Loading:
break
case .NoResults:
showNothingFoundLabel()
case .Results(let list):
tileButtons(list)
}
}
private func hideSpinner(){
view.viewWithTag(1000)?.removeFromSuperview()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit{
print("deinit \(self)")
for task in downloadTasks{
task.cancel()
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
SearchViewController
import UIKit
class SearchViewController: UIViewController,UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate {
private struct TableViewCellIdentifier {
static let searchResultCell = "SearchResultCell"
static let nothingFoundCell = "NothingFoundCell"
static let loadingCell = "LoadingCell"
}
// MARK: LandscapeViewController
override func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.willTransitionToTraitCollection(newCollection, withTransitionCoordinator: coordinator)
switch newCollection.verticalSizeClass{
case .Compact:
showLandscapeViewWithCoordinator(coordinator)
case .Regular,.Unspecified:
hideLandscapeViewWithCoordinator(coordinator)
}
}
private func showLandscapeViewWithCoordinator(coordinator: UIViewControllerTransitionCoordinator){
precondition(landscapeViewController == nil)
landscapeViewController = storyboard?.instantiateViewControllerWithIdentifier("LandscapeViewController") as? LandscapeViewController
if let controller = landscapeViewController{
controller.search = search
controller.view.frame = view.frame
controller.view.alpha = 0
view.addSubview(controller.view)
addChildViewController(controller)
coordinator.animateAlongsideTransition({ _ in
if self.presentedViewController != nil{
self.dismissViewControllerAnimated(true, completion: nil)
}
self.searchBar.resignFirstResponder()
controller.view.alpha = 1
}, completion: { _ in
controller.didMoveToParentViewController(self)
})
}
}
private func hideLandscapeViewWithCoordinator(coordinator: UIViewControllerTransitionCoordinator){
if let controller = landscapeViewController{
controller.willMoveToParentViewController(nil)
coordinator.animateAlongsideTransition({ _ in
controller.view.alpha = 0
}, completion: { _ in
if self.presentedViewController != nil {
self.dismissViewControllerAnimated(true, completion: nil)
}
controller.view.removeFromSuperview()
controller.removeFromParentViewController()
self.landscapeViewController = nil
})
}
}
private func showNetworkError(){
let alert = UIAlertController(title: "Whoops...", message: "There was an error reading from the iTunes Store. Please try again.", preferredStyle: .Alert)
let action = UIAlertAction(title: "OK", style: .Default, handler: nil)
alert.addAction(action)
presentViewController(alert, animated: true, completion: nil)
}
// MARK: Detail ViewController
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowDetail" {
switch search.state{
case . Results(let list):
let indexPath = sender as! NSIndexPath
let searchResult = list[indexPath.row]
let detailViewController = segue.destinationViewController as! DetailViewController
detailViewController.searchResult = searchResult
default:
break
}
}
}
// MARK: Properties
#IBOutlet weak var searchBar: UISearchBar!
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var segmentedControl: UISegmentedControl!
let search = Search()
private var landscapeViewController: LandscapeViewController?
// MARK: Methodes
#IBAction func segmentedControl(sender: UISegmentedControl) {
performSearch()
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.contentInset = UIEdgeInsets(top: 108, left: 0, bottom: 0, right: 0)
tableView.rowHeight = 80
searchBar.becomeFirstResponder()
configureNib(nibName: TableViewCellIdentifier.searchResultCell)
configureNib(nibName: TableViewCellIdentifier.nothingFoundCell)
configureNib(nibName: TableViewCellIdentifier.loadingCell)
}
private func configureNib(nibName nibName: String){
let cellNib = UINib(nibName: nibName, bundle: nil)
tableView.registerNib(cellNib, forCellReuseIdentifier: nibName)
}
// MARK: UISearchBarDelegate
func searchBarSearchButtonClicked(searchBar: UISearchBar){
performSearch()
}
private func performSearch() {
if let category = Search.Category(rawValue: segmentedControl.selectedSegmentIndex){
search.performSearchForText(searchBar.text!, category: category){
success in
if !success{
self.showNetworkError()
}
if let controller = self.landscapeViewController{
controller.searchResultsRecived()
}
self.tableView.reloadData()
}
tableView.reloadData()
searchBar.resignFirstResponder()
}
}
func positionForBar(bar: UIBarPositioning) -> UIBarPosition {
return .TopAttached
}
// MARK: TableView
// MARK: - UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch search.state{
case .NotSearchedYet:
return 0
case .Loading,.NoResults:
return 1
case .Results(let list):
return list.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch search.state{
case .NotSearchedYet:
fatalError("Should never get here")
case .Loading:
let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifier.loadingCell, forIndexPath: indexPath)
let spinner = cell.viewWithTag(100) as! UIActivityIndicatorView
spinner.startAnimating()
return cell
case .NoResults:
return tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifier.nothingFoundCell, forIndexPath: indexPath)
case .Results(let list):
let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifier.searchResultCell, forIndexPath: indexPath) as! SearchResultCell
let searchResult = list[indexPath.row]
cell.configureForSearchResult(searchResult)
return cell
}
}
// MARK: UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
performSegueWithIdentifier("ShowDetail", sender: indexPath)
}
func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
switch search.state{
case .NotSearchedYet,.NoResults,.Loading:
return nil
case .Results:
return indexPath
}
}
}
This is a bug in the Swift compiler, you'll want to file a radar with Apple to report this. There's nothing you can do about it otherwise.
I had this error because I had a switch of an enum with a case that contain an Array payload (don't ask me why, I don't know).
I think the enum is the search state inside the tableView:cellForRowAtIndexPath: method of SearchViewController and the prepareForSegue: method of LandscapeViewController (the .Result case contain a list).
In my case, changing the payload to a Set instead of an Array worked. (as a workaroud until it's fixed)

Resources