Install Realm in a Swift App - ios

I am trying to add Realm to my app written in swift. I have followed the tutorial and I can't seem to get it to work. The biggest problem is that when I try to import Realm I get No such module 'Realm' I don't know what else to try. You can see my efforts below.
You can see the instructions here: http://realm.io/docs/cocoa/0.85.0/#swft
I have also copied the instructions below:
Due to the current lack of proper infrastructure for Swift dependency management, using Realm in your project requires the following steps:
Add Realm as a submodule by opening the Terminal, cd-ing into your top-level project directory, and entering the command git submodule add git#github.com:realm/realm-cocoa.git
Open the realm-cocoa folder, and drag Realm.xcodeproj into the file navigator of your Xcode project.
In Xcode, navigate to the target configuration window by clicking on the blue project icon, and selecting the application target under the “Targets” section in the sidebar.
In the tab bar at the top of that window, open the “Build Phases” panel.
Expand the “Target Dependencies” gorup, and add Realm’s iOS framework.
Expand the “Link Binary with Libraries” group, and add Realm’s iOS framework as well as libc++.dylib.
Click on the + button at the top left of the panel and select “New Copy Files Phase”. Rename this new phase to “Copy Frameworks”, set the “Destination” to “Frameworks”, and add Realm.framework.
Drag the file at realm-cocoa/Realm/Swift/RLMSupport.swift into the file navigator of your Xcode project, unchecking the “Copy items if needed” checkbox.
Below is what it looks like in my project:

I am not sure exactly why this isn't working, but here is a workaround:
Follow the latest instructions.
Create a bridging header, for example by
Add a new Objective-C class to your xcode project.
Agree to have a bridging header created
Delete the Objective-C class
Add this in the bridging header:
#import "Realm/Realm.h"
Remove any Import Realm statements from your code, including from RLMSupport.swift
Now it should work. For example, I test with putting this in my ViewController.swift
import UIKit
class Person: RLMObject {
dynamic var name = ""
dynamic var birthdate = NSDate(timeIntervalSince1970: 1)
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let author = Person()
author.name = "David Foster Wallace"
// Get the default Realm
let realm = RLMRealm.defaultRealm()
// Add to the Realm inside a transaction
realm.beginWriteTransaction()
realm.addObject(author)
realm.commitWriteTransaction()
// Print all Persons
println(Person.allObjects())
}
}
Which prints:
RLMArray <0x7a243760> (
[0] Person {
name = David Foster Wallace;
birthdate = 1970-01-01 00:00:01 +0000;
}
)

I have been talking with the guys at Realm, and it turns out that the latest instructions don't work with Realm <= 0.85 They changed they way the build the framework and it won't work anymore. They said they will release 0.86 later today that should fix the problems anyone is having with Swift. In the meantime I have a test project that anyone can take the latest framework from. https://github.com/smitt04/testRealm
Version 0.86 is now out and this is no longer an issue.

The Swift installation instructions were long and convoluted, so I'm not surprised you and several other users ran into issues.
Please follow the latest installation instructions here.

Related

Installing third party Objective-C library within Swift 3 / Xcode 8 (SharkORM)

Im pretty new to Xcode/Swift and want to install a third party library(SharkORM).
I drag'n'dropped the folder "SharkORM" into XCode and selected "Create groups". Then i created a file "Swift-Bridging-Header.h" and typed in #include “SharkORM.h” as described in the documentation. When i hold CMD and click on it it leads me to the interface declaration(good!?). Now when i try to use it: class MyClass: SRKObject { ... } i get an error: "Use of undeclared type 'SRKObject'". But i can CMD+click on it which leads me to the interface declaration again.
I tried to install with Cocoapod, too, with no success.
As posted on GitHub, it sounds like the header file you created has not been added to the build settings as the chosen bridging header.
That is the most likely scenario leading to the object not being defined in your swift code.
Check, if SharkORM.h contains SRKObject declaration. If not, find header file with it and place it to bridging header too

Use of unresolved identifier 'Realm'

I am new to both Realm and iOS development and I am stuck due to this error. I downloaded the latest version of Realm i.e. 0.98.0 and followed the steps mentioned in the Getting Started section
Download the latest release of Realm and extract the zip.
Go to your Xcode project’s “General” settings. Drag RealmSwift.framework and Realm.framework from the ios/swift-2.1.1/, watchos/, tvos/ or osx/swift-2.1.1/ directory to the “Embedded Binaries” section. Make sure Copy items if needed is selected and click Finish.
In your unit test target’s “Build Settings”, add the parent path to RealmSwift.framework in the “Framework Search Paths” section.
If using Realm in an iOS, watchOS or tvOS project, create a new “Run Script Phase” in your app’s target’s “Build Phases” and paste the following snippet in the script text field:
bash "${BUILT_PRODUCTS_DIR}/${FRAMEWORKS_FOLDER_PATH}/Realm.framework/strip-frameworks.sh"
As mentioned in the answer to the following question I added $(PROJECT_DIR) in the Framework Search Paths
How to add the parent path to RealmSwift.framework in the “Framework Search Paths” section?
After that I created a class called Dog and added the following code in AppDelegate.swift
let myDog = Dog()
myDog.name = "Rex"
myDog.age = 1
print("name of dog: \(myDog.name)")
// Get the default Realm
let realm = try! Realm()
// Persist your data easily
try! realm.write {
realm.add(myDog)
}
When I try to build the project I get an error "Use of unresolved identifier 'Realm'" on the following line :
let realm = try! Realm()
I have tried creating new projects and carefully following the above steps but I still get the error. For Step 2 I tried added the framework with both the "Create groups" and "Create folder references" options while keeping "Copy items if needed" checkbox ticked.
I am using XCode 7.2.1, OS 10.11.13 and Swift 2.1.1. I do not have Cocoapods installed at the moment
Am I missing some step somewhere? Any help would be really appreciated.
The issue was the missing import statement. The examples folder helped in solving the issue.
import RealmSwift
Having worked with Java and the auto import feature in Eclipse this took a little getting used to.

Unable to integrate ZXingObjC in a iOS Swift Project

Im working on an iOS project, which shows the customer number in a barcode. I had installed the framework ZXingObjC with CocoaPods, described in GitHub.
I can compile my Project without errors. I can also use the classes of ZXingObjC in my Objective-C classes, without errors. After than, I have added the import Command #import <ZXingObjC/ZXingObjC.h> to my bridging header file, like my other custom objective-c classes, without compile errors. (I had testet the header file by destroying some import statements and got the expected file not found exception.)
But now, I can't use any class of ZXingObjC in my swift classes. I only got the following compile error: Use of undeclared type '...'. The Xcode autocomplete is not working, too.
e.g.
var test : ZXMultiFormatWriter?
>> Use of undeclared type 'ZXMultiFormatWriter'
I tried:
setup new project, same issue
checked header search path: $(SRCROOT)/Pods/Headers/Public/Adjust
reinstalled the ZXingObjC framework
checked build settings: Enable Modules: YES
checked build settings: Other Linker Flags: $(inherited) -ObjC
-framework "ZXingObjC"
checked linked binaries in the build phases: framework is added
checked import statement in the bridging header file (#import
<ZXingObjC/ZXingObjC.h> and #import "ZXingObjC/ZXingObjC.h" -- no
difference)
Windows style: restarting Xcode and Mac ;-)
I'm using:
Xcode: 6.3.2
CocoaPods: 0.37.2
Project Deployment target: iOS 8.0
SDK: 8.3
Does anyone know the problem? Can anyone help?
How can I make the ZXingObjC framework available in swift?
Actually it is an easy issue:
Podfile
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!
pod 'ZXingObjC', '~> 3.1'
So, on terminal:
cd workspace
pod install
Then, once opened project on Xcode, you have to edit bridging-header adding ZXingObj:
#import <ZXingObjC/ZXingObjC.h>
Finally, in your swift classes that uses ZXingObjC, you have to import ZXingObjC.
import ZXingObjC
class ZXingObjCWrapper {
func encode() {
let writer = ZXMultiFormatWriter.writer()
....
}
}
The rest of the code for when you need to set an UIImage with this bar code:
func generateDataMatrixQRCode(from string: String) -> UIImage? {
do {
let writer = ZXMultiFormatWriter()
let hints = ZXEncodeHints() as ZXEncodeHints
let result = try writer.encode(string, format: kBarcodeFormatDataMatrix, width: 1000, height: 1000, hints: hints)
if let imageRef = ZXImage.init(matrix: result) {
if let image = imageRef.cgimage {
return UIImage.init(cgImage: image)
}
}
}
catch {
print(error)
}
return nil
}
The header search path was not correct in my project. The right values are:
$(inherited)
"${PODS_ROOT}/Headers/Public"
"${PODS_ROOT}/Headers/Public/ZXingObjC"
The second and third lines were not added by installation with CocoaPods.
EDIT: The installed framework have to be added to "Embedded Binaries" in General tab of the project.
I tried everything on this page to add ZXingObjC as a Pod. My goal was to generate an Aztec barcode.
I checked my Header Search Path. As Reddas said, I had to manually add "${PODS_ROOT}/Headers/Public/ZXingObjC". I also added ZXingObjC as an Embedded Binary (in the General Tab).
I checked my bridging file & all was good. I checked my view controllers where I wanted to generate the barcode. The import ZXingObjC was there.
No compile errors. But I can't declare a variable of ZXingObjC.
No luck. Any more suggestions?
EDIT - I went into the Targets, Build Settings and searched for Header Search Paths. I added in BOTH "${PODS_ROOT}/Headers/Public/ZXingObjC" and "${PODS_ROOT}/Headers/Private/ZXingObjC"
This seemed to unclog whatever broke. It works now. Strangely, I can now even delete those entries and it works.

How to import and use SDWebImage in swift xcode 6.3.1

Im new to Swift and now making a project that includes showing many photos from the web and I understand that I need to use SDWebImage.
I saw related questions here and in other places but all are in Objective-C syntax and not working for me.
What I did till now:
I downloaded the zip from GitHub
Copied SDWebImage folder to my folder
Tried all possible combinations for import
#import <"SDWebImage/UIImageView+WebCache.h">
import SDWebImage/UIImageView+WebCache.h
etc..
Can someone please help me import it
Firstly, you need configure Bridging Header, it is described here at SO. Use the following:
#import <SDWebImage/UIImageView+WebCache.h>
This will import Objective-C code to Swift code
Secondly, just use it, like:
self.imageView.sd_setImageWithURL(self.imageURL)
As far as I understood you already have a Bridging header and only need to organize your imports. Since you copied the source files directly into your project without using cocoapods or Carthage you do the import like this:
#import "UIImageView+WebCache.h"
Swift 3.0 code
import SDWebImage
let url = URL.init(string: "https://vignette3.wikia.nocookie.net/zelda/images/b/b1/Link_%28SSB_3DS_%26_Wii_U%29.png")
imagelogo.sd_setImage(with: url , placeholderImage: nil)
In swift 5.1 simply import the SdWebimage and use extenion
extension UIImageView{
func downloadImage(url : String, placeHolder : UIImage?) throws{
if let url = URL(string: url){
self.sd_imageIndicator?.startAnimatingIndicator()
self.sd_setImage(with: url) { (image, err, type, url) in
if err != nil{
self.sd_imageIndicator?.stopAnimatingIndicator()
print("Failed to download image")
}
self.sd_imageIndicator?.stopAnimatingIndicator()
}
}
}
}
The only way it worked for me (using mac os 10.11.4 and ios 9.3) was this:
download and unpack framework from link: https://github.com/rs/SDWebImage/releases/download/3.6/SDWebImage-3.6.framework.zip:
drag that framework into x-code project and check option: Copy items if needed (In project navigator you should now see suitcase icon containing a folder with .h files)
create new bridging header file: cmd+n -> file -> new -> file... and select "header" template icon
open that file, write line (just above #endif:) #import < SDWebImage/UIImageView+WebCache.h > (this is path of one of header files from framework)
the most important step from #Azat answer above, is to connect the file you just made with project, in build settings:
select project name (blue icon in Project navigator)
select "Build Settings" on your right start to type "Bridging header..." and when you have row containing "Objective-C Bridging header"
press twice in empty field in that row (window pops-up), and drag bridging header file from Project navigator into that window.
hopefully now you can use library methods as: imageView.setImageWithUrl(url, placeholderImage:)

Xcode 6.0.1 Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1

I am getting this error on archive:
Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1
How to solve it?
Please see the screenshot.
This problem occurs when the Swift optimization level is not set to None for Release. Set the value to None and the issue goes away.
Open up your project and click on the projects root directory.
Click the build settings tab.
Search for Swift Compiler - Code Generation and under Optimization Level make sure Release is set to None.
EDIT
After upgrading to Xcode 6.1 these instructions caused other issues when archiving (building for debug/device worked fine). Setting the optimization to Fastest allowed me to archive again. There are apparent issues with Swift compiling still (archiving specifically).
Can't archive working 6.0.1 Swift project in Xcode 6.1 / Segmentation fault: 11
EDIT
I was not able to fund the Build Settings tab, until I read this answer.
how to find the build settings tab
This occurred for me when I had two of the exact same files, and also when I was missing I file I didn't know I had deleted. I clicked on the error message, and just above the error, it shows you what file you have more than 1 of or are missing.
You can click the Product in the navigation and choose the "Clean" button; it will clean all compile error in your project. Then, you can debug for the latest error.
Deleted files reference keep in Build Phase and that's why it gives this error. Remove reference from there as well.
Project> Target > Build Phase
Under this section you will find your deleted files in red colour. Remove these files error will resolve.
I am not sure if it has one solution.
I recommend you to check the differences between your last git commit, and comment on/off the changes.
In my case, my code was
let anArray = ResultDict["ResultSet"] as [[NSDictionary : AnyObject]]
for aDict : NSDictionary in anArray {
let anObject = ObjectType(ObjectDict: aDict)
objectList.addObject(aDict)
}
no warning on the line, i got the same exit 1 compile error
then i changed it to the below it has compiled.
let anArray = ResultDict["ResultSet"] as [[NSDictionary : AnyObject]]
for aDict in anArray {
let anObject = ObjectType(ObjectDict: aDict)
objectList.addObject(aDict)
}
I don't know if this is really an answer, but...
I had the same issue. App worked when building/running, but archiving failed with "...swiftc failed with exit code 1", with no other helpful message at all. Luckily, when I tried to build my app with Nomad's ipa build, I got:
The following build commands failed:
CompileSwift normal arm64 /path/to/erroneous/TableViewController.swift
So I started commenting out sections of that file and tracked the problem down to a tuple assignment.
// MARK: - Table Data
private var tableData: [(sectionName: String, item:ListItem)] = []
private func refreshTableData() {
// let labor = ("Labor", laborListItem) // DOESN'T ARCHIVE
let labor = (sectionName: "Labor", item: laborListItem) // ARCHIVES
tableData = [labor]
tableView.reloadData()
}
So apparently the compiler wanted the elements in thast tuple named (as defined by the type of tableData).. but only for archiving? The Dumb thing is, I use this same pattern in other view controllers, and the compiler seems to be fine with those.
For the record my Code Generation -> Optimization Level was set to None for debug and release.
Hope this helps someone! It took hours to figure this out.
It happened to me when I didn't put the parenthesis at the end of a call of a function:
let var = self.getNextPrimeNumber
solved it by:
let var = self.getNextPrimeNumber()
In my case, it was caused by duplicate files, using the same name, in my project directory. As soon as I removed them, the error was gone.
This happened to me when I used static inline function from swift file
The function looks like this
static inline void openURLInSafari(NSString * _Nonnull urlString) {
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlString]];}
I just had the same thing occur. I hunted down the cause to one file that caused the error even when empty. Examining the file, I discovered it had the wrong character set. When I set it to UTF-8, the error vanished. I think that it was decoding it with the wrong character set.
From this I surmise that the error simply indicates that something has happened that the compiler was unprepared for. Sorry that isn't very helpful to most people, but it may help to check your characters sets.
one more case that can lead to this error which just took me hours to track down: a failable initializer that always returns nil.
i had an initializer that looked like this:
init?(object: MyObject) {
if object.importantProperty {
// initialize
}
return nil
}
when what i meant was:
init?(object: MyObject) {
if object.importantProperty {
// initialize
}
else {
return nil
}
}
fixing the initializer made the error go away.
If using Core Data:
I had a Core Data entity for which I created the NSManagedObject subclasses (with Xcode's help). In addition, the entity was configured to generate code automatically (see screenshot), so basically 2 classes existed during runtime. Just switch the option to Manual/None and it won't generate it.
This error occurred for me after I noticed that a few of my .swift files were inexplicably in the wrong directory -- one level above my Xcode project directory. When I noticed this, I moved them into the main project directory and cleaned the project, thinking everything would be fine. However, upon building the project I got the above-mentioned "failed with exit code 1" error. Just above the error message it listed the files I had just moved, indicating that it couldn't find them in the directory where they used to be. In addition to the error message, the files I moved were now showing up as red in the file navigation pane.
For each of the files in question what I did to resolve this was:
- Select the file from the list of files in the Xcode file navigation pane,
- Click on the little page icon in the rightmost pane of Xcode, which opens a file attributes pane,
- Click on the little folder icon underneath where it says "Location" in the file attributes pane,
- Choose the new location for the file,
- RESTART Xcode for the above changes to really do anything.
this error comes from missing files so the compiler couldn't find the files and keep alerting.
Follow these steps to rebuild your app:
Look up for the red and invisible files within workspace
Remove their reference
Re-add files
Re-compile
I experienced this error after performing a git merge. I solved new Xcode warnings and the project can be compiled.
Xcode 7.2.1 is used in my case.
In my way the error was due to UIDevice.currentDevice() in ((UIDevice.currentDevice().systemVersion as NSString).floatValue >= 8.0)
After commenting this all starts work fine.
XCode 7.2
in my case , at your project target Build Setttings, in Other Swift Flags,jsut delete the String "-serialize-debuggin-options"
enter image description here
I had a resolution very similar to RyanM, where with an excess of hubris I tried to assign a variable to the default value of an inner function:
Fails to compile (though does not crash SourceKit):
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
func itemCell(_ indexPath: IndexPath = indexPath) -> UITableViewCell {//...}
Succeeds:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
func itemCell(_ indexPath: IndexPath) -> UITableViewCell {//...}
One possible reason that this can happen is perhaps because you have deleted a file but not removed references to it. This will mess up the pbxproj file. I would check to see if that is the case.
check "Development Pods" Folder all listed Frameworks path.
In my case swift development snapshot was selected instead of xcode 9.2. here are the steps and image.
keep xcode on screen and click on xcode top menu bar.
Than go to toolchains option and check on xcode 9.2. thats it.
Happy Coding!!!
So, I had the above and narrowed it down to a TFS issue with locking the file but only when I pasted or did any other edits besides small copies or manual typing. I noticed the original file would compile, but my edits wouldn't, even though they were syntactic OK. Also related is unable to save document: xcode The document "..." could not be saved
The fix for both was:
Duplicate working version.
Paste fully-merged new code into duplicate.
Copy and paste old file over new one. (I personally just renamed the old one to something else, then pasted duplicate and renamed it, too. Guessing both work since I pasted directly earlier for reverts during tests to see).
Voila. Lazy way to bypass merge-locking issue. Apparently full file-pastes are just fine, while edits aren't. Shared since the other answers don't seem to be as lazy as this. ;)
Note: I am suspecting a non-UTF-8 character made its way somewhere, but pastes worked in older versions so I don't know where, or if relevant.
In my case, the error was the result of missing files that were generated by Xcode. I tried the regular clean Opt+Shift+K and it didn't clean up all the errors. I found a post on the Apple Developer site that recomended going to the Product Menu in Xcode, holding down the opt key, and selecting Clean Build Folder. This appears to be a more comprehensive build as it pops up a modal dialog for you to confirm.
Just go to the "project setting" and click on the "build phaces" after that you will find targets in that u have to delete the test file like my project name "WER" so its showing like this WER&TEST so just delete that and clean ur project and run .........

Resources