相机应用程序与集合视图

时间:2017-06-30 01:05:54

标签: ios swift xcode

我是XCode和Swift的新手。希望你们能帮助我。我遇到一个问题,当我单击相机按钮,拍摄照片并单击“使用照片”时,相机将被解除并再次返回主页面。

我真正想要的是: 当我单击“使用照片”时,主页面应该在集合视图中以缩略图大小显示刚刚拍摄的图像。 Camera Example The expected output

这是我的代码:

import UIKit
import CoreLocation
import Photos
import PhotosUI
import MessageUI

let albumName = "CP"

class SpeakerViewController: UIViewController, 
CLLocationManagerDelegate, UIImagePickerControllerDelegate, 
UINavigationControllerDelegate, UICollectionViewDataSource, 
UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, 
MFMailComposeViewControllerDelegate {
@IBOutlet var lblLocation: UILabel!
@IBOutlet var tvNews: UITextView!
@IBOutlet var tapView: UIView!
@IBOutlet var btnAlbum: UIButton!
@IBOutlet var btnCamera: UIButton!
@IBOutlet var btnSend: UIButton!

let locationManager = CLLocationManager()
let geoCoder = CLGeocoder()

var latitude = [String]()
var longitude = [String]()
var tap : UITapGestureRecognizer! = UITapGestureRecognizer()
var assetCollection: PHAssetCollection! = PHAssetCollection()

var photoAsset : PHFetchResult<PHAsset>!

var albumFound : Bool = false
var sendLocation : String = ""
var sendContent : String = ""
var imageArray = [UIImage]()
var isCamera : Bool = false

@IBAction func btnBack(_ sender: AnyObject) {
    PHPhotoLibrary.shared().performChanges({
        PHAssetChangeRequest.deleteAssets(self.photoAsset)
        }, completionHandler: {(success, error) in
            NSLog("Delete image => %@", (success ? "Success" : "Error"))
            self.navigationController?.dismiss(animated: true, completion: nil)
    })
}

override func viewDidLoad() {
    super.viewDidLoad()
    LocalStore.setActiveView("speaker")
    self.navigationController?.navigationBar.isTranslucent = false
    self.navigationController?.navigationBar.barTintColor = UIColor(red: 255/255, green: 237/255, blue: 0/255, alpha: 1.0)

    if(locationManager.responds(to: #selector(CLLocationManager.requestAlwaysAuthorization))) {
        locationManager.requestAlwaysAuthorization()
    }
    locationManager.delegate = self

    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.startUpdatingLocation()

    tap = UITapGestureRecognizer(target: self, action: #selector(SpeakerViewController.DismissKeyboard))
    let fetchOptions = PHFetchOptions()
    fetchOptions.predicate = NSPredicate(format: "title = %@", albumName)
    let collection:PHFetchResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)

    if let first_Obj:AnyObject = collection.firstObject{
        //found the album
        self.albumFound = true
        self.assetCollection = first_Obj as! PHAssetCollection
    } else {
        var albumPlaceholder:PHObjectPlaceholder!
        NSLog("\nFolder \"%@\" does not exist\nCreating now...", albumName)
        PHPhotoLibrary.shared().performChanges({
            let request = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: albumName)
            albumPlaceholder = request.placeholderForCreatedAssetCollection
            },

            completionHandler: {success, error in
                if(success){
                    print("Successfully created folder")
                    self.albumFound = true
                    let collection = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [albumPlaceholder.localIdentifier], options: nil)
                    self.assetCollection = collection.firstObject as PHAssetCollection!
                } else {
                    print("Error creating folder")
                    self.albumFound = false
                }
        })
    }

    NotificationCenter.default.addObserver(self,
        selector: #selector(SpeakerViewController.keyboardShow(_:)),
        name: NSNotification.Name.UIKeyboardDidShow,
        object: nil)

    NotificationCenter.default.addObserver(self,
        selector: #selector(SpeakerViewController.keyboardHide(_:)),
        name: NSNotification.Name.UIKeyboardDidHide,
        object: nil)

    NotificationCenter.default.addObserver(self,
        selector: #selector(SpeakerViewController.applicationBecameActive(_:)),
        name: NSNotification.Name.UIApplicationDidBecomeActive,
        object: nil)

    NotificationCenter.default.addObserver(self,
        selector: #selector(SpeakerViewController.applicationBecameInactive(_:)),
        name: NSNotification.Name.UIApplicationWillResignActive,
        object: nil)
}

/* Start listening for iCloud user change notifications */
func applicationBecameActive(_ notification: Notification){
    print("did become active notification")
    if LocalStore.getPostIdMenu() != "0" {
        self.navigationController?.dismiss(animated: true, completion: nil)
        LocalStore.setPostIdMenu("0")
    }
}

func applicationBecameInactive(_ notification: Notification){
    print("did become inactive notification")
    LocalStore.setPostIdMenu("0")
}

func keyboardShow(_ notification: Notification) {
    print("Keyboard Show")
    self.view.addGestureRecognizer(tap)
}

func keyboardHide(_ notification: Notification){
    print("Keyboard Hide")
    self.view.removeGestureRecognizer(tap)
}

override func viewWillAppear(_ animated: Bool) {
    //fetch the photo from the collection
    self.navigationController?.hidesBarsOnTap = false
    self.photoAsset = PHAsset.fetchAssets(in: self.assetCollection, options: nil)
    self.collectionView.reloadData()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    let alertView = UIAlertController(title: "出现错误", message: "无法检索您的位置", preferredStyle: .alert)
    alertView.addAction(UIAlertAction(title: "好的", style: .default){ _ in})
    self.present(alertView, animated: true, completion: nil)
}



func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    latitude.removeAll()
    longitude.removeAll()

    let currentLocation = locations.last!

    print("didUpdateToLocation: \(currentLocation)")

    latitude.append(String(format: "%.8f", currentLocation.coordinate.latitude))
    longitude.append(String(format: "%.8f", currentLocation.coordinate.longitude))

    print("Latitude \(latitude.count), Longtitude \(longitude.count)")

    geoCoder.reverseGeocodeLocation(currentLocation, completionHandler: {(placemarks, error) -> Void in
        if(error == nil && placemarks!.count > 0 ) {
            let placeMark = placemarks![0] as CLPlacemark

            if (placeMark.addressDictionary?["Thoroughfare"] as? String) != nil {

                self.lblLocation.text = "\(placeMark.thoroughfare!), \(placeMark.postalCode!), \(placeMark.administrativeArea!)"
                print("Location \(placeMark.locality!)\(placeMark.country!)")
                self.locationManager.stopUpdatingLocation()
                self.sendLocation = self.lblLocation.text!
            } else {
                print("thoroughfare not found, reupdate coordinate")
                self.locationManager.delegate = self
                self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
                self.locationManager.startUpdatingLocation()
            }
        } else {
            NSLog("%@", error.debugDescription)
        }
    })
}

func DismissKeyboard() {
    view.endEditing(true)
}

@IBOutlet var collectionView: UICollectionView!
@IBAction func btnAlbum(_ sender: AnyObject) {
    isCamera = false

    if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.savedPhotosAlbum)) {
        let imagePicker : UIImagePickerController = UIImagePickerController()
        imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
        imagePicker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
        imagePicker.delegate = self
        imagePicker.allowsEditing = false
        self.present(imagePicker, animated: true, completion: nil)
    }
}

@IBAction func btnCamera(_ sender: AnyObject) {
    isCamera = true
    if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)) {
        let imagePicker : UIImagePickerController = UIImagePickerController()
        imagePicker.sourceType = UIImagePickerControllerSourceType.camera
        imagePicker.delegate = self
        imagePicker.allowsEditing = false
        self.present(imagePicker, animated: true, completion: nil)
    } else {
        let alert = UIAlertController(title: "出现错误", message: "您的手机没有相机", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "好的", style: .default, handler: {(alertAction) in
            alert.dismiss(animated: true, completion: nil)
        }))

        self.present(alert, animated: true, completion: nil)
    }
}

@IBAction func btnSend(_ sender: AnyObject) {
    var count : Int = 0
    if(self.photoAsset != nil) {
        count = self.photoAsset.count
    }

    if (tvNews.text != "" && count > 0) {
        sendContent = tvNews.text

        if (MFMailComposeViewController.canSendMail()) {
            let emailTitle = "App"
            let messageBody = "位置: \(sendLocation) \n\n \(sendContent) \n\n "
            let toReceipients = ["test@com"]
            let mc : MFMailComposeViewController = MFMailComposeViewController()
            mc.mailComposeDelegate = self
            mc.setSubject(emailTitle)
            mc.setMessageBody(messageBody, isHTML: false)
            mc.setToRecipients(toReceipients)
}
            for image in self.imageArray {
                let photoData : Data = UIImagePNGRepresentation(image)!
                mc.addAttachmentData(photoData, mimeType: "image/png", fileName: "CP.png")
            }

            self.present(mc, animated: true, completion: nil)
        } else {
            print("No email account found")
        }
    } else {
        let alertView = UIAlertController(title: "出现错误", message: "没有内容或照片", preferredStyle: .alert)
        alertView.addAction(UIAlertAction(title: "好的", style: .default, handler: {(alertAction) in
            alertView.dismiss(animated: true, completion: nil)
        }))
        self.present(alertView, animated: true, completion: nil)
    }
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    var count : Int = 0
    if(self.photoAsset != nil) {
        count = self.photoAsset.count
    }

    return count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell: PhotoCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! PhotoCollectionViewCell
    let asset : PHAsset = self.photoAsset[(indexPath as NSIndexPath).item] as PHAsset

    PHImageManager.default().requestImage(for: asset, targetSize: PHImageManagerMaximumSize, contentMode: .aspectFill, options: nil, resultHandler: {(result, info) in
        if let image = result {
            cell.setThumbnailImage(image)
            self.imageArray.append(image)
        }
    })

    return cell
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if(segue.identifier == "viewLargePhoto") {
        if let controller:ViewPhotoViewController = segue.destination as? ViewPhotoViewController {
            if let cell = sender as? UICollectionViewCell {
                if let indexPath: IndexPath = self.collectionView.indexPath(for: cell) {
                    controller.index = (indexPath as NSIndexPath).item
                    controller.photoAsset = self.photoAsset
                    controller.assetCollection = self.assetCollection
                }
            }
        }
    }
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 4
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 1
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if(isCamera) {
        let image = info["UIImagePickerControllerOriginalImage"] as! UIImage
        PHPhotoLibrary.shared().performChanges({
            let createAssetRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
            let assetPlaceholder = createAssetRequest.placeholderForCreatedAsset
            if let albumChangeRequest = PHAssetCollectionChangeRequest(for: self.assetCollection,              
                assets: self.photoAsset as PHFetchResult<PHAsset>) {

                let enumeration: NSArray = [assetPlaceholder!]
                albumChangeRequest.addAssets(enumeration)
            }
            //CORRECTION Error : App crashes
            }, completionHandler: {(success, error) in
                NSLog("Adding Image to Library => %@",(success ? "Success" : "Error!"))
                //Relocated1

        })
        //CORRECTION Relocated1

        picker.dismiss(animated: true, completion: nil)

    } else {
        let image = info["UIImagePickerControllerOriginalImage"] as! UIImage
        PHPhotoLibrary.shared().performChanges({
            let createAssetRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
            let assetPlaceholder = createAssetRequest.placeholderForCreatedAsset
            if let albumChangeRequest = PHAssetCollectionChangeRequest(for: self.assetCollection,

                assets: self.photoAsset as PHFetchResult<PHAsset>) {

                let enumeration: NSArray = [assetPlaceholder!]
                albumChangeRequest.addAssets(enumeration)
            }
            }, completionHandler: {(success, error) in
                NSLog("Adding Image to Library => %@",(success ? "Success" : "Error!"))
                picker.dismiss(animated: true, completion: nil)
                //self.navigationController?.dismiss(animated: true, completion: nil)
        })
    }
}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    picker.dismiss(animated: true, completion: nil)
}

func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
    switch result {
    case .cancelled:
        let alertView = UIAlertController(title: "取消电邮", message: "您已经取消电邮", preferredStyle: .alert)
        alertView.addAction(UIAlertAction(title: "好的", style: .default, handler: {(alertAction) in
            alertView.dismiss(animated: true, completion: nil)
        }))
        self.present(alertView, animated: true, completion: nil)
    case .saved:
        let alertView = UIAlertController(title: "保存电邮", message: "您已经保存电邮", preferredStyle: .alert)
        alertView.addAction(UIAlertAction(title: "好的", style: .default, handler: {(alertAction) in
            alertView.dismiss(animated: true, completion: nil)
        }))
        self.present(alertView, animated: true, completion: nil)
    case .sent:
        let alertView = UIAlertController(title: "发送电邮", message: "您已经发送您的电邮", preferredStyle: .alert)
        alertView.addAction(UIAlertAction(title: "好的", style: .default, handler: {(alertAction) in
            alertView.dismiss(animated: true, completion: nil)
        }))
        self.present(alertView, animated: true, completion: nil)
    case .failed:
        let alertView = UIAlertController(title: "发送失败", message: "请检查您的电邮设定", preferredStyle: .alert)
        alertView.addAction(UIAlertAction(title: "好的", style: .default, handler: {(alertAction) in
            alertView.dismiss(animated: true, completion: nil)
        }))
        self.present(alertView, animated: true, completion: nil)
    //CORRECTION default:
      //  break
    default :
        break
    }

    self.dismiss(animated: false, completion: nil)
  }
}

提前致谢!

0 个答案:

没有答案