我正在选择一个按钮的项目并在具有表视图的另一个视图控制器上弹出地址簿。问题是应用程序在手机上崩溃但在模拟器中没有崩溃。
第一个视图的代码在这里:
import UIKit
import MobileCoreServices
import Parse
class MainPageViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var btnAddress : UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Overview"
btnAddress.layer.cornerRadius = 5;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func getAddressBook (sender : AnyObject){
self.performSegueWithIdentifier("AddressController", sender: self);
}
@IBAction func MyVideosClicked(sender: AnyObject) {
}
@IBAction func RecordButtonClicked(sender: AnyObject) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {
println("captureVideoPressed and camera available.")
var imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .Camera;
imagePicker.mediaTypes = [kUTTypeMovie!]
imagePicker.allowsEditing = false
imagePicker.showsCameraControls = true
self.presentViewController(imagePicker, animated: true, completion: nil)
}
else {
println("Camera not available.")
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject: AnyObject]) {
let tempImage = info[UIImagePickerControllerMediaURL] as! NSURL!
let pathString = tempImage.relativePath
self.dismissViewControllerAnimated(true, completion: {
})
// save video to library
UISaveVideoAtPathToSavedPhotosAlbum(pathString, self, nil, nil)
var videoData = NSData(contentsOfFile:pathString!)
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
var dataPath = paths.stringByAppendingPathComponent("myalbum")
if (!(NSFileManager.defaultManager().fileExistsAtPath(dataPath)))
{
NSFileManager.defaultManager().createDirectoryAtPath(dataPath, withIntermediateDirectories: false, attributes: nil, error: nil)
}
var dateFormat = NSDateFormatter()
dateFormat.dateFormat = "dd-MM-yyyy-HH:mm:SS"
var now = NSDate()
var dateStr = dateFormat.stringFromDate(now)
// var getImagePath = paths.stringByAppendingPathComponent("/SavedFile.mov")
var videopath = dataPath + "/" + dateStr + ".mov"
var success = videoData?.writeToFile(videopath, atomically: false)
if((success) != nil)
{
println(videopath)
performSegueWithIdentifier("VideoList", sender: nil)
}
else
{
println("Not Saved")
}
}
@IBAction func leftSideButtonTapped(sender: AnyObject) {
var appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.drawerContainer!.toggleDrawerSide(MMDrawerSide.Left, animated: true, completion: nil)
}
}
以下是第二个视图的代码:
import UIKit
import AddressBookUI
import AddressBook
import MessageUI
import CoreLocation
class AddressController: UIViewController,UITableViewDataSource,UITableViewDelegate,MFMessageComposeViewControllerDelegate,CLLocationManagerDelegate,LocationDelegate, ABPeoplePickerNavigationControllerDelegate {
let locationManager = CLLocationManager()
var Locality : String = "";
var contactsArray = NSMutableArray();
var contactList = NSMutableArray();
var contactNumberArray = NSMutableArray();
var indexPathArr = NSMutableArray();
var isLocation : Bool = true;
// let addressBookRef: ABAddressBook?;
var addressBookRef: ABAddressBookRef?
var titleArray : NSArray = ["#","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var sectionDictionary = NSMutableDictionary();
var errorMessage : String = "";
@IBOutlet weak var tblContacts : UITableView?;
func createAddressBook(){
var error: Unmanaged<CFError>?
addressBookRef = ABAddressBookCreateWithOptions(nil, &error).takeRetainedValue()
}
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization();
self.locationManager.requestAlwaysAuthorization();
var b = UIBarButtonItem(title: "Send", style: .Plain, target: self, action: "sendMessage:")
var image = UIImage(named: "settings.png")
image = image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
var settingBtn = UIBarButtonItem(image: image, style: UIBarButtonItemStyle.Plain, target: self, action: "LocationChange");
self.navigationItem.rightBarButtonItems = [settingBtn,b];
// Do any additional setup after loading the view.
tblContacts?.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell");
switch ABAddressBookGetAuthorizationStatus(){
case .Authorized:
println("Already authorized")
createAddressBook()
/* Access the address book */
case .Denied:
let alert = UIAlertView (title: "SmsPush", message: "Denied access to address book. Go to Setting->Privacy->Contacts to enable Contact access!", delegate: nil, cancelButtonTitle: "Ok");
alert.show()
return;
case .NotDetermined:
createAddressBook()
if let theBook: ABAddressBookRef = addressBookRef{
ABAddressBookRequestAccessWithCompletion(theBook,
{(granted: Bool, error: CFError!) in
if granted{
println("Access granted")
} else {
println("Access not granted")
}
})
}
case .Restricted:
let alert = UIAlertView (title: "SmsPush", message: "Access restricted", delegate: nil, cancelButtonTitle: "Ok");
alert.show()
println("Access restricted")
return;
default:
let alert = UIAlertView (title: "SmsPush", message: "Other Problem", delegate: nil, cancelButtonTitle: "Ok");
alert.show()
println("Other Problem")
return;
}
self.locationManager.startUpdatingLocation()
contactsArray = ABAddressBookCopyArrayOfAllPeople(addressBookRef).takeRetainedValue() as! NSMutableArray
for contactObject in contactsArray{
let contactName = ABRecordCopyCompositeName(contactObject).takeRetainedValue() as String;
contactList.addObject(contactName);
}
let ansArray = sorted(contactList,{ (s1, s2) in
return s1.localizedStandardCompare(s2 as! String) == NSComparisonResult.OrderedAscending
})
contactList = NSMutableArray(array: ansArray);
}
//TableView Methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return titleArray.count;
}
func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]! {
return self.titleArray as [AnyObject];
}
func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
return index;
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return titleArray.objectAtIndex(section) as? String;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let resultPredicate = NSPredicate(format:"SELF beginswith[c] %@",titleArray.objectAtIndex(section) as! String
)
var sectionArrayList : NSArray = contactList.filteredArrayUsingPredicate(resultPredicate)
sectionDictionary.setValue(sectionArrayList.mutableCopy() as! NSMutableArray, forKey: titleArray.objectAtIndex(section) as! String)
return sectionArrayList.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tblContacts!.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell;
var str = "\(indexPath.section)-\(indexPath.row)";
if(indexPathArr.containsObject(str)){
cell.accessoryType = .Checkmark;
}else{
cell.accessoryType = .None;
}
var sectionTitle: String = titleArray.objectAtIndex(indexPath.section) as! String
var sectionContacts: NSArray = sectionDictionary.objectForKey(sectionTitle) as! NSArray
cell.textLabel?.text = sectionContacts.objectAtIndex(indexPath.row) as? String;
return cell;
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let oldCell = tableView.cellForRowAtIndexPath(indexPath);
var sectionTitle: String = titleArray.objectAtIndex(indexPath.section) as! String
var sectionContacts: NSArray = sectionDictionary.objectForKey(sectionTitle) as! NSArray
for contactNames in contactsArray{
if(sectionContacts.objectAtIndex(indexPath.row) as? String == ABRecordCopyCompositeName(contactNames).takeRetainedValue() as String?){
var str = "\(indexPath.section)-\(indexPath.row)";
if(oldCell!.accessoryType == .Checkmark){
if(indexPathArr.containsObject(str)){
contactNumberArray.removeObject(contactNames)
indexPathArr.removeObject(str);
break;
}
}else{
if(indexPathArr.count >= 3){
let alert = UIAlertView (title: "SmsPush", message: "You can select maximum of 3 recipients", delegate: nil, cancelButtonTitle: "Ok");
alert.show()
return;
}
contactNumberArray.addObject(contactNames)
indexPathArr.addObject(str);
break;
}
break;
}
}
tableView.reloadData();
println("\(indexPathArr.count)");
}
//AddressBook functions
func promptForAddressBookRequestAccess() {
var err: Unmanaged<CFError>? = nil
ABAddressBookRequestAccessWithCompletion(addressBookRef) {
(granted: Bool, error: CFError!) in
dispatch_async(dispatch_get_main_queue()) {
if !granted {
println("Just denied")
self.displayCantAddContactAlert()
} else {
println("Just authorized")
}
}
}
}
func openSettings() {
let url = NSURL(string: UIApplicationOpenSettingsURLString)
UIApplication.sharedApplication().openURL(url!)
}
func displayCantAddContactAlert() {
let cantAddContactAlert = UIAlertController(title: "Cannot Add Contact",
message: "You must give the app permission to add the contact first.",
preferredStyle: .Alert)
cantAddContactAlert.addAction(UIAlertAction(title: "Change Settings",
style: .Default,
handler: { action in
self.openSettings()
}))
cantAddContactAlert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
presentViewController(cantAddContactAlert, animated: true, completion: nil)
}
// Send Message functions
@IBAction func sendMessage(sender: AnyObject) {
if(indexPathArr.count>3){
let alert = UIAlertView (title: "SmsPush", message: "You can select maximum of 3 recipients", delegate: nil, cancelButtonTitle: "Ok");
alert.show()
return;
}else if(indexPathArr.count==0){
let alert = UIAlertView (title: "SmsPush", message: "No recipients are selected to send message", delegate: nil, cancelButtonTitle: "Ok");
alert.show()
return;
}else{
var messageVC = MFMessageComposeViewController()
if (!MFMessageComposeViewController.canSendText()) {
let alert = UIAlertView (title: "SmsPush", message: "Simulator does not support Messaging.", delegate: nil, cancelButtonTitle: "Ok");
alert.show()
return;
}
if(Locality == ""){
Locality = "Unavailable"
}
if(NSUserDefaults.standardUserDefaults().objectForKey("LocationValue") != nil){
isLocation = NSUserDefaults.standardUserDefaults().objectForKey("LocationValue") as! Bool;
}
if(isLocation){
messageVC.body = "This is a default Message and My location is \(Locality)";
}else{
messageVC.body = "This is a default Message and My location is Unavailable";
}
var numberArray = NSMutableArray();
var numberString : String = "";
var i : Int = 0;
for phoneObject in contactNumberArray{
var phoneNumber : ABMultiValueRef = ABRecordCopyValue(phoneObject, kABPersonPhoneProperty).takeRetainedValue()
var tempNumber : String = ABMultiValueCopyValueAtIndex(phoneNumber, 0).takeRetainedValue() as! String;
numberArray.addObject(tempNumber);
}
if(numberArray.count==1){
messageVC.recipients = ["\(numberArray.objectAtIndex(0))"];
}else if(numberArray.count==2){
messageVC.recipients = ["\(numberArray.objectAtIndex(0))","\(numberArray.objectAtIndex(1))"];
}else if(numberArray.count==3){
messageVC.recipients = ["\(numberArray.objectAtIndex(0))","\(numberArray.objectAtIndex(1))","\(numberArray.objectAtIndex(2))"];
}
messageVC.messageComposeDelegate = self;
self.presentViewController(messageVC, animated: false, completion: nil)
}
}
func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) {
switch (result.value) {
case MessageComposeResultCancelled.value:
println("Message was cancelled")
self.dismissViewControllerAnimated(true, completion: nil)
case MessageComposeResultFailed.value:
println("Message failed")
self.dismissViewControllerAnimated(true, completion: nil)
case MessageComposeResultSent.value:
println("Message was sent")
self.dismissViewControllerAnimated(true, completion: nil)
default:
break;
}
}
//Location related functions
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
errorMessage = "";
if(manager.location.coordinate.latitude != 0 && manager.location.coordinate.longitude != 0){
CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: { (placemarks, error) -> Void in
if (error != nil) {
println("Error:" + error.localizedDescription)
return
}
if placemarks.count > 0 && placemarks != nil {
let pm = placemarks[0] as! CLPlacemark
self.displayLocationInfo(pm)
}else {
println("Error with data")
}
})
}
}
func displayLocationInfo(placemark: CLPlacemark) {
self.locationManager.stopUpdatingLocation()
if(placemark.subLocality != nil){
Locality = placemark.subLocality
}else if(placemark.locality != nil){
Locality = placemark.locality
}else if(placemark.administrativeArea != nil){
Locality = placemark.administrativeArea
}else if(placemark.administrativeArea != nil){
Locality = placemark.country
}else{
Locality = "Unavailable";
}
println("\(Locality)");
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
errorMessage = "Please enable Location Service for SmsPush";
println("Error: " + error.localizedDescription)
}
func locationCheck(isEnabled: Bool) {
if(isEnabled){
isLocation = true;
}else{
isLocation = false;
}
}
func LocationChange(){
// self.storyboard?.instantiateViewControllerWithIdentifier("LocationViewController")
self.performSegueWithIdentifier("LocationViewController", sender: self);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// 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.
}
*/
}
我真的不明白为什么应用程序崩溃了。有什么想法吗?