i have problem when i want to making folder in document directory
when i making the folder first time like folder (Hello) and when i try to make another folder like (hello) in small letter not anything doing and the folder not creating i don't know why ? but if i try to making the folder (hello ) with small space it is ok and it is display it on the table view i don't know why and if any one can check the folder hello and Hello is different
please help
the following is the code
#IBAction func btnMakeFolder(sender: AnyObject) {
var checkFoundAlbum:Bool = false // for check the folder if is found it or not
let c = NSCharacterSet.whitespaceCharacterSet()
if folderNameTextField.text?.stringByTrimmingCharactersInSet(c) != "" {
let fileManager = NSFileManager.defaultManager()
do {
let document = try fileManager.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
// her i check the album is he exists or not
let getFolders = try fileManager.contentsOfDirectoryAtURL(document, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles)
for folder in getFolders {
if folder.lastPathComponent!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) == folderNameTextField.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()){
checkFoundAlbum = true
}else {
checkFoundAlbum = false
}
}
// her for create folder and display the alert for the user
if checkFoundAlbum == false{
let folderUrl = document.URLByAppendingPathComponent(folderNameTextField.text!)
try fileManager.createDirectoryAtURL(folderUrl, withIntermediateDirectories: true, attributes: nil)
self.dismissViewControllerAnimated(true, completion: nil)
}else {
let alertController = UIAlertController(title: "Album Exists", message: "This Album Already Exists,Please Change The Name", preferredStyle: .Alert)
let alertAction = UIAlertAction(title: "OK", style: .Default, handler: { (alertAction:UIAlertAction) in
})
alertController.addAction(alertAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
}catch {
print(error)
}
}else {
alert()
}
}
I suggest to try this code on an actual device – the iOS simulator is usually not case sensitive assuming the underlying filesystem of the simulator uses HFS+.
Related
I am giving users the possibility to set up Project-Details in an app.
Since there is also the opportunity to upload an image, i will have to make use of Firebase Storage. Because I want to give the users an overview of their projects combining the data and the uploaded picture I need to make a reference between the DocumentID in database and the ImageID in storage.
I thought about a two step approach: 1. Users are generating a Project -> User clicks "next" (document getting generated) 2. User uploads an image -> Image gets stored in Storage with Reference to the DocumentID of the just generated Project.
The goal is simply to link the Image to the Document ID of the project.
Can anyone give me a hint how to solve that problem? Here are my codes so far:
For the Project-Details:
// MARK: Store the Project Infos in Database
// Check the fields and validate that the data is correct. If everything is correct, this method returns nil. Otherwise, it returns the error message
func validateFields() -> String? {
// Check that all fields are filled in
if txtLocation.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
txtProjectTitle.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
txtProjectDescription.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
endDate.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
beginnDate.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
return "Please fill in all fields."
}
return nil
}
#IBAction func saveProject(_ sender: Any) {
let user = Auth.auth().currentUser
if let user = user {
let uid = user.uid
// Validate the fields
let error = validateFields()
if error != nil {
// There is something wrong with the fields, show error message
showError(error!)
} else {
// Create cleaned versions of the data
let projectTitle = txtProjectTitle.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let projectLocation = txtLocation.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let projectDescription = txtProjectDescription.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let projectBeginn = beginnDate.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let projectEnd = endDate.text!.trimmingCharacters(in: .whitespacesAndNewlines)
// Save stuff
let db = Firestore.firestore()
db.collection("Projects").addDocument(data: ["Project Title": projectTitle, "Project Location": projectLocation, "Project Description": projectDescription, "Project Start": projectBeginn, "Project Finish": projectEnd, "uid": uid]) { (error) in
if error != nil {
// Show error message
self.showError("Error saving user data")
}
}
}
} else { self.showError("Please log out and log in again")}
}
// Error Handling for save
func showError(_ message:String) {
errorLabel.text = message
errorLabel.alpha = 1
}
And for the Image upload
//MARK: Imagepicker
// Image Picker functions
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
newImage.image = image
picker.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
// MARK: - Actions
// Image Picker
#IBAction func addImage(_ sender: Any) {
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
let actionSheet = UIAlertController(title: "Photo Source", message: "Choose a source", preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (action: UIAlertAction) in imagePickerController.sourceType = .camera
self.present(imagePickerController, animated: true, completion: nil)
}))
actionSheet.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: { (action: UIAlertAction) in imagePickerController.sourceType = .photoLibrary
self.present(imagePickerController, animated: true, completion: nil)
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(actionSheet, animated: true, completion: nil)
}
//MARK: Upload Image
#IBAction func uploadImage(_ sender: Any) {
guard let image = newImage.image, let data = image.jpegData(compressionQuality: 1.0) else {
self.showError("Something went wrong")
return
}
let imageName = UUID().uuidString
let imageReference = Storage.storage().reference()
.child("imagesFolder")
.child(imageName)
imageReference.putData(data, metadata: nil) {(metadata, err) in
if let err = err {
self.showError("Something went wrong")
return
}
imageReference.downloadURL(completion: { (url, err) in
if let err = err {
self.showError("Something went wrong")
return
}
guard let url = url else {
self.showError("Something went wrong")
return
}
let dataReference = Firestore.firestore().collection("imageReferences").document()
let documentUid = dataReference.documentID
let urlString = url.absoluteString
let imageUID = documentUid
let data = ["Image UID": imageUID, "Image URL": urlString]
dataReference.setData(data, completion: {(err) in
if let err = err {
self.showError("Something went wrong")
return
}
UserDefaults.standard.set(documentUid, forKey: imageUID)
})
})
}
}
// Error Handling for save
func showError(_ message:String) {
errorLabel.text = message
errorLabel.alpha = 1
}
So in best case I could do this even in one View Controller without the need of a two step approach. If it is not possible I would like to put the generated Document ID in
let data = ["Image UID": imageUID, "Image URL": urlString]
of
let dataReference = Firestore.firestore().collection("imageReferences").document()
let documentUid = dataReference.documentID
let urlString = url.absoluteString
let imageUID = documentUid
let data = ["Image UID": imageUID, "Image URL": urlString]
dataReference.setData(data, completion: {(err) in
if let err = err {
self.showError("Something went wrong")
return
}
I would be very pleased if someone could help me. :)
The problem that I'm facing is that I have successfully created the array and have displayed the values like so:
Users
-uid
- Name: Example
- Profile Pic URL: example12345
- email: example#example.co.uk
However, in another swift file I have successfully generated a personality type and am struggling to add this to the array so that I end up with something that looks like this:
Users
-uid
- Name: Example
- Profile Pic URL:
- email: example#example.co.uk
- personality type: INTJ
I have tried copying the code from the previous swift class to no avail
This is the code for the working firebase array
#IBAction func createAccountAction(_ sender: AnyObject) {
let usersRef = Database.database().reference().child("Users")
let userDictionary : NSDictionary = ["email" : emailTextField.text!, "Name": nameTextField.text!]
if emailTextField.text == "" {
let alertController = UIAlertController(title: "Error", message: "Please enter your email and password", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
} else {
Auth.auth().createUser(withEmail: self.emailTextField.text ?? "", password: self.passwordTextField.text ?? "") { (result, error) in
if error != nil {
let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
return
}
guard let user = result?.user else { return }
let vc = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController
self.present(vc, animated: true, completion: nil)
// HERE YOU SET THE VALUES
usersRef.child(user.uid).setValue(userDictionary, withCompletionBlock: { (error, ref) in
if error != nil { print(error); return }
let imageName = NSUUID().uuidString
let storageRef = Storage.storage().reference().child("profile_images").child("\(imageName).png")
if let profileImageUrl = self.profilePicture.image, let uploadData = UIImageJPEGRepresentation(self.profilePicture.image!, 0.1) {
storageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
if error != nil, metadata != nil {
print(error ?? "")
return
}
storageRef.downloadURL(completion: { (url, error) in
if error != nil {
print(error!.localizedDescription)
return
}
if let profileImageUrl = url?.absoluteString {
self.addImageURLToDatabase(uid: user.uid, values: ["profile photo URL": profileImageUrl as AnyObject])
}
})
})
}
}
)}
}
}
This is the other swift file function which generates the personality type which I would like to add to the array
#IBAction func JPbtn(_ sender: Any) {
if (Judging < Perceiving){
Result3 = "P"
} else {
Result3 = "J"
}
let PersonalityType = "\(Result) \(Result1) \(Result2) \(Result3)"
print(PersonalityType)
let vc = self.storyboard?.instantiateViewController(withIdentifier: "Example") as! ViewController
self.present(vc, animated: true, completion: nil)
}
So if you are just trying to add a new key with a value, all you need to do is create a new reference like this.
guard let currentUserUID = Auth.auth().currentUser?.uid else { return }
print(currentUserUID)
let userPersonalityRef = Database.database().reference().child("users").child(currentUserUID).child("personality")
userPersonalityRef.setValue("Some Value")
When you set the value it can also be a dictionary if you want. But if your users don't all have personality make sure it optional on your data model or else It might crash your app. When you are getting your user from firebase.
I know the downloadURL function has been deprecated, but I can't seem to get the new completion function to work:
#IBAction func postButtonClicked(_ sender: Any) {
let mediaFolder = Storage.storage().reference().child("media")
if let data = UIImageJPEGRepresentation(postImage.image!, 0.5) {
mediaFolder.child("\(uuid).jpg").putData(data, metadata: nil, completion: { (metadata, error) in
if error != nil {
let alert = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: UIAlertControllerStyle.alert)
let okButton = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
alert.addAction(okButton)
self.present(alert, animated: true, completion: nil)
} else {
let imageURL = mediaFolder.downloadURL(completion: { (url, error) in
if error != nil {
print("error!!!!")
} else {
return url?.absoluteString
}
})
print(imageURL)
}
})
}
}
I just can't get this to work. I always get the error!!!!! message in the log and I'm not sure why. I've been struggling with this code for the past 3 hours and for some reason I just can't get the imageURL to print.
All I want is to get imageURL to equal url?.absoluteString
Any help would greatly be appreciated
You're not getting the URL to print out because you're not querying the right storage references.
First, check if the image is actually uploaded in the storage and then add the child Id to your mediaFolder in the else statement:
mediaFolder.child("\(uuid).jpg").downloadURL(completion: { (url, error) in
})
I am developing an iOS app that allows user to save urls, similar to the Pocket app. In the app I have a share extension that basically just save the url into a NSUserDefaults based on the app group. For some reason the share extension causes the mobile safari to hang (being non responsive) after selecting the share extension. The code for the share extension is so simple, I am wondering what may have caused it. On debugging in Xcode, the function in the share extension is not being called at all too it seems. Any clues? This is running on iOS 9.3.
Here is the code:
//
// ShareViewController.swift
// intrafeedappShare
//
// Created by Dicky Johan on 5/21/16.
// Copyright © 2016 Dicky Johan. All rights reserved.
//
import UIKit
import Social
import MobileCoreServices
class ShareViewController: UIViewController {
var selectedURL: String?
override func viewDidLoad() {
super.viewDidLoad()
let contentType = kUTTypeURL as String
guard let item = self.extensionContext?.inputItems.first as? NSExtensionItem else {
fatalError()
}
for attachment in item.attachments as! [NSItemProvider] {
if attachment.hasItemConformingToTypeIdentifier(contentType) {
attachment.loadItemForTypeIdentifier(kUTTypeURL as String, options: nil) { url, error in
if error == nil {
guard let url = url as? NSURL else {
self.extensionContext?.cancelRequestWithError(NSError(domain:"Url is empty",code:-1,userInfo: nil))
return
}
self.selectedURL = url.absoluteString
let defaults = NSUserDefaults(suiteName: Constants.Settings.sharedAppGroup)
if let arrUrls = defaults!.objectForKey(Constants.Settings.sharedURLS) {
// append to the existing list
arrUrls.appendString(url.absoluteString)
} else {
let newArrUrl = [url.absoluteString]
defaults!.setObject(newArrUrl, forKey: Constants.Settings.sharedURLS)
}
defaults!.synchronize()
self.extensionContext?.completeRequestReturningItems(nil, completionHandler: nil)
let alert = UIAlertController(title: "Success", message: "Added url to intrafeed", preferredStyle: .Alert)
let action = UIAlertAction(title: "Done", style: .Default) { _ in
self.dismissViewControllerAnimated(true, completion: nil)
}
alert.addAction(action)
self.presentViewController(alert, animated: true, completion: nil)
} else {
self.extensionContext?.cancelRequestWithError(error)
let alert = UIAlertController(title: "Error", message: "Error loading url", preferredStyle: .Alert)
let action = UIAlertAction(title: "Error", style: .Cancel) { _ in
self.dismissViewControllerAnimated(true, completion: nil)
}
alert.addAction(action)
self.presentViewController(alert, animated: true, completion: nil)
}
}
}
}
}
}
Ok, apparently there was a crash in the code, thus causing the Safari to freeze. On debugging the extension in Xcode, I found the issue.
I developed an application and one of the functionalities is to see a video that I downloaded from a server. I'm using Alamofire to access the network, this is my code:
func GetVideoFiedMedia(videoFiedData: VideofiedVideo?, completionHandler: (NSURL?, NSError?) -> ()) {
var result: NSURL? = nil;
let parameters : [ String : AnyObject] = [
"CnxID": (videoFiedData?.cnxID!)!,
"TaskNum": (videoFiedData?.taskNum!)!,
"Ev_File": (videoFiedData?.evFile!)!
]
let headers = [
"Content-Type": "application/json"
]
let urlAux = "https://xxxxxx/xxxxx/xxxxx.svc/VideoMedia?";
Alamofire.request(.POST, urlAux, parameters: parameters, headers: headers, encoding: .JSON)
.validate()
.responseString { response in
switch response.result {
case .Success:
if let JSON = response.result.value {
do{
let data: NSData = JSON.dataUsingEncoding(NSUTF8StringEncoding)!
let decodedJson = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves) as! NSDictionary
let dObj = decodedJson["d"] as! NSDictionary;
let resultSet = dObj["Media"] as? NSArray;
if(resultSet != nil){
let stringsData = NSMutableData();
for item in resultSet! {
let byte = item as! Int;
var char = UnicodeScalar(byte);
stringsData.appendBytes(&char, length: 1)
}
var destinationUrl: NSURL? = nil;
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! as NSURL;
let fileName = "msavid.mp4";
destinationUrl = documentsUrl.URLByAppendingPathComponent(fileName)
let fileMangr = NSFileManager.defaultManager()
var fileHandle = NSFileHandle.init(forWritingAtPath: (destinationUrl?.path!)!)
if(fileHandle == nil){
fileMangr.createFileAtPath((destinationUrl?.path!)!, contents: stringsData, attributes: nil)
fileHandle = NSFileHandle.init(forWritingAtPath: (destinationUrl?.path!)!)
}
if(fileHandle != nil){
fileHandle?.seekToEndOfFile();
fileHandle?.writeData(stringsData);
fileHandle?.closeFile();
}
result = destinationUrl;
completionHandler(result, nil);
}
}catch{
result = nil;
completionHandler(result, nil);
}
}
case .Failure(let error):
completionHandler(result, error);
}
}
}
When I got the nsurl for the video I played it in this way:
_ = self.manager.GetVideoFiedMedia(videoFiedItem, completionHandler: { responseObject, error in
if(responseObject != nil){
var sendSegue = false;
self.nsurl = responseObject;
if NSFileManager().fileExistsAtPath(responseObject!.path!) == true {
if(sendSegue == false){
self.performSegueWithIdentifier("sureViewSegue", sender: nil);
self.nsurl = nil;
sendSegue = true;
MBProgressHUD.hideAllHUDsForView(self.view, animated: true);
}
}else{
MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
let alert = UIAlertController(title: "Alert", message: "We have problem to download the media data, please try again later.", preferredStyle: UIAlertControllerStyle.Alert);
alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil));
self.presentViewController(alert, animated: true, completion: nil);
}
}else{
MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
let alert = UIAlertController(title: "Alert", message: "We have problem to download the media data, please try again later.", preferredStyle: UIAlertControllerStyle.Alert);
alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil));
self.presentViewController(alert, animated: true, completion: nil);
}
})
The segue that I performed push a AVPlayerViewController.
When I was testing the method using the iOS simulator everything seems to work fine, the problem came when I tried to use the functionality in a real device(iPhone or iPad)the video doesn't show up, I got the AVPlayerViewController with this symbol that can't reproduce the video.
Please any help on this, I can't figure out what is causing the problem.
So simple and at the same time unthinkable, just reset the device and erase the copy of the file msavid.mp4 in the phone and it is working.