How to save/retrieve data to a user without account (Parse + Swift) - swift

How can I use Parse to save a user's data without them having an account but still know which phone uploaded the content? For example, if a user uploads an image, how can I display that image back to only the person who uploaded it- all without requiring the user to create an account?
Thanks in advance for any help/direction!

You could use the Installations table in your data browser:
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
// Store the deviceToken in the current Installation and save it to Parse
let installation = PFInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation.saveInBackground()
}
That is how you link an installation to a device. You can then add a custom column to the Installation table in your data browser such as a File or array of images, whatever works for you.

If it's all within a current user session an anonymous user may work for you: https://parse.com/docs/ios/guide#users-anonymous-users

Related

How to solve Swift FileManager couldn’t open file because of permission and implement file access

I made a music app for macOS that need the access of the file on disk. I can get the proper url, but I can't access the file. To figure out that problem, here I create a concise code snippet to concentrate on the question itself.
.onAppear {
var url = FileManager.default.homeDirectoryForCurrentUser
url.appendPathComponent("Downloads/Test.txt")
var text: String = ""
do {
text = try String(contentsOf: url)
} catch {
print("ERROR: \(error.localizedDescription)")
}
}
The output would be like this
ERROR: The file “Test.txt” couldn’t be opened because you don’t have permission to view it.. So I noticed App Sandbox in Targets > Signing & Capabilities. But at the list of file access (as you can see in the following picture), there's only User Selected File, Downloads Folder, Pictures Folder, Music Folder and Movie Folder. So I come up with 3 questions:
What that User Selected File means? Is that means that the user can select some specific file for my app to access? If it is, how can user selects them?
How can I get access to other folders like Desktop Folder if I remain the App Sandbox capability here?
I also noticed the trash icon on right-upper corner. If I delete App Sandbox, I can access every folder I want with the user's agreement by a default system pop-up. But what the deletion of App Sandbox means? Does it make my app "untrusted" somehow when user install it or others? Does it cause any security problems?
And It couldn't be better if you can tell me the conventions major developers follow when meet this problem. I would highly appreciate your help.

Open any email attachment inside the ios app

I want to open any email attachments with my iOS app. Means from my iOS app I want to open email and if there is any attachments(like pdf), I want to open this attachment with my app.I am able to open email app from my app with the following code
if let mailURL = URL(string: "message:") {
if UIApplication.shared.canOpenURL(mailURL) {
UIApplication.shared.open(mailURL, options: [:], completionHandler: nil)
}
}
After that how to open any attachments inside the iOS app. can any one help me. Can I save the attachments to my documents Directory?
Actually my requirement is from my app I will go to the mail box. If any attachment present there, I have to open it with my app. Not only I want to open it with my app, but also I want to save the file in my documents directory.
You can't tell the Mail app what to do so what you want is not exactly possible.
What you can do is add your app in the "Open In" menu by supporting some file types. So that when the user taps the attachment your app will appear in the list of apps.
You can do that this way:
Add the file types your app can handle. Follow the instructions here: https://developer.apple.com/library/archive/qa/qa1587/_index.html
Once 1. is done add the following function in your AppDelegate:
func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {
// do what you want with file
}
To save the file in your app's document directory you can see how it's done here:
https://programmingwithswift.com/save-file-to-documents-directory-with-swift/

Firebase Offline Support: upload posts while user is offline and sync when user comes online in iOS Swift app

I am using firebase in an iOS-Swift project in which I have to enable offline support for uploading posts, in the post there is a picture and caption just like Instagram, so what I want is when user is offline and he/she wants to upload a post, his/her picture get saved in cache and when user comes online that photo get uploaded and give back a download url that we can use for saving posts-details it in database.
sample code is:
let photoIDString = UUID().uuidString
let storageRef = Storage.storage().reference(forURL: "storage ref URL").child("posts").child(photoIDString)
storageRef.putData(imageData, metadata: nil, completion: { (metadata, error) in
guard let metadata = metadata else {
return
}
if error != nil {
return
}
storageRef.downloadURL(completion: { ( url, error ) in
guard let downloadURL = url else {
return
}
let photoUrl = downloadURL.absoluteString
self.sendDataToDatabase(photoUrl: photoUrl)
})
}
)
I want to know what changes should I make in my code to provide the offline capability. Any code snippet will help more.
The problem is better view as re-send to server when there is an error.
For your offline case, you can check if the error return is a network error, or manually check network connection availability.
You can create a re-send array of object
e.g
var resendList : [YourObjectType]
// when failed to send to server
resendList.append(yourFailedObject)
And then, 2 solutions:
Check the network connectivity manually and reupload in when the app become active in func applicationDidBecomeActive(_ application: UIApplication) in appDelegate. For checking connectivity you can try the method here: Check for internet connection with Swift But this has a problem that, the user has to go out the app and back again with network connected
Keep track(listen to notification) on the connectivity change, using a suggestion method by https://stackoverflow.com/a/27310748/4919289 and reupload it to server
and loop through all objects in resendList and re-upload again.
I am not an iOS developer, but I can share logical flow and some references.
When user clicks on upload: Check if network is available?
if yes: upload the post.
if no:
save the post to app storage or offline database
set broadcast receiver to receive broadcast when device comes online. This link may be helpful.
upload post when device comes online.
If you are looking for solution that is offered by Firebase, you may find more details here.
Firebase offers you plenty of ways to do this in their documentation. https://firebase.google.com/docs/database/ios/offline-capabilities
When uploading to the firebase server, it will queue itself and wait until it has a internet connection again to upload. If this happens to timeout or you want to do it your own way just attempt to upload with a completionHandler on the setValue or updateChild functions - if not successfully and the error message is because of internet, add it to a local cache to the phone with the data and the path to the firebase server.
onLoad, attempt the same upload again until it succeeds, once it succeeds - clear the local cache.

App to open in Spanish when participant clicks on Spanish Website in iOS

I have a project and this project support two languages English and Spanish.
If the user has Spanish languages selected phone, the app opens Spanish. The same cycle works for English also.
Second, We have a website and this website provides Spanish and English support. User can register ( Sign Up ) or login (Sign In)
from English site or Spanish site.
My question, As a User if I choose to register via the Spanish site, I should be taken to the app in Spanish and not English.
How can I do this? Universal Link or Deep Link. Is there anyone build this cycle previously?
You cannot change the device's language from within an app.
A solution for your use case could be to manually handle localization in your project: instead of relying on NSLocalizedString you'd have to use your own function for providing the localization for a given string/key. In the "normal" usage scenario you'd use the preferred language of the system; when opening the app via a link you'd add the language as URL parameter and use that language for the app session. (Note that this will not work with Storyboard or Info.plist localizations, only with texts you explicitly set in code).
Use Branch iOS SDK for deep linking so that you can ensure that a user receives the language even when they don't have the app installed before hand. In your links you should be able to set a field language to english, epanish, etc. When ever a user opens your application you can just pull that information out of the Branch callback like so.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:[UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// listener for Branch Deep Link data
Branch.getInstance().initSession(launchOptions: launchOptions) { (params, error) in
// do stuff with deep link data (nav to page, display content, etc)
print(params as? [String: AnyObject] ?? {})
let language = params?['language']
//Store this in their NSUserDefaults
let defaults = UserDefaults.standard.set(language, forKey: "language")
}
return true
}
The information in your UserDefaults will persist until the user deletes the app and reinstalls it.
let language = UserDefaults.standard.string(forKey: 'language')

Associate app download with device? (Swift)

How can I associate a user's device with my app? I want to have it so the user doesn't create an account but their data is still saved and retrieved to their phone so I need a way to associate their phone with my app. I'm using Parse to save user data.
I'm trying to use device token and I'm wondering if this is the correct approach. Any ideas would be greatly appreciated.
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let installation = PFInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation.save()
}
You can simply use anonymous users with Parse. They've introduced them a few years because you can't get the UDID anymore and still may want to identify your users.
You can simply login an anonymous user on startup with the following command:
if (![PFUser currentUser]) { //we check if the user is already logged in
[PFAnonymousUtils logInWithBlock:^(PFUser *user, NSError *error) {
if (!error) {
//user has been logged in
}
}];
}
This will create an anonymous user in your userbase and they will be able to write data to your database. Anonymous users can be logged out and behave like normal users. There is also a possibility to merge them to a signed up user.
Here is a blog post from Parse, with some additional information. Their docs are usually also quite helpful.
EDIT: in case you have trouble converting the code to swift, here is the equivalent code in swift (taken from the docs, available here):
PFAnonymousUtils.logInWithBlock {
(user: PFUser?, error: NSError?) -> Void in
if error != nil || user == nil {
println("Anonymous login failed.")
} else {
println("Anonymous user logged in.")
}
}