Saving images on Xcode simulator - ios

I'm trying to save images using their file paths but every time that I kill the Xcode simulator and restart it, the location of the images changes and my imageView is blank. I know for a fact that the location changes because I print out the file path when I try to pick an image from the photo library and it's different each time.
I access the URL of the UIImage
let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
let url = info[UIImagePickerController.InfoKey.imageURL] as! URL
After which I save the URL as a string to my realm database. I've tried converting it to string via all of these
let imageFilePath = url.relativeString
let imageFilePath = url.absoluteString
let imageFilePath = url.relativePath
but none of them worked. I'm a newbie to Swift so let me know if I've missed any key details needed.

Related

How to upload image with parameter multipart in swift

I attached the screen shot of request and response. How to pass this type of parameter, i am not able add this type parameter in request. Please make a structure/sample so i can use in my code. Any clarification/suggestion please let me know. thanks in Advance.
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as String
let imageName = "imageClicked.png" // name of the image to be saved.
//let localPath = documentDirectory.appending(imageName)
// imageName which you have stored in the db at retrieval time
let imagePath = String("\(documentDirectory)/\(imageName)")
let fileName = (UIImage(named: imagePath)?.pngData())!
// Here i am selecting the image from source and getting the image path and converting into data. then getting the error.
// if i am taking image from app and converting into data getting the response.
// Passing the image from App
let fileName = (UIImage(named: "swift_file.png")?.pngData())!

how to load image from local image path Ios Swift 4

I have one JSON which contain path of images from one local folder of Project as Followed
The issue is i want to get image from that path, How do i achieve it?
I had try to convert String to URL and set URL as Image using Kingfisher Library
let url = URL(string: "/VWiOSProjects/CollageMakerDemo/Development/CollageMaker/CollageMaker/Goodies.xcassets/Goodies-1.imageset/Goodies-1.png")!
cell.imgTool.kf.setImage(with: url)
But it don't work I had Tried this one also
let url = URL(string: "/VWiOSProjects/CollageMakerDemo/Development/CollageMaker/CollageMaker/Goodies.xcassets/Goodies-1.imageset/Goodies-1.png")!
let imageData:NSData = NSData(contentsOf: url)!
let image = UIImage(data: imageData as Data)
cell.imgTool.image = image
NOTE: I can't upload this JSON file on Server, I need to use it Locally
I have solved my issue using fileURLWithPath
let url = URL.init(fileURLWithPath: "/VWiOSProjects/CollageMakerDemo/Development/CollageMaker/CollageMaker/Goodies.xcassets/Goodies-1.imageset/Goodies-1.png")
let imageData:NSData = NSData(contentsOf: url)!
let image = UIImage(data: imageData as Data)
cell.imgTool.image = image
If the images are in Assets(*.xcassets) folder, the you can access it by init(named:) method.
cell.imgTool.image = UIImage(named: "img1")
Actually you no need to store the entire path. You could store image names in array or something.
In my point of view, the best way is to add All Images to *.xcassets folder.(Because you have preloaded 5-10 images)
In case you needs to display it in collection view or TableView,
let imageName = "Goodies-\(indexPath.row)"
cell.imgTool.image = UIImage(named: imageName)
If images are in assets folder itself then go for #Lal Krishna's method. And if they are on server then you should add http:// or https:// and the URL of server followed by JSON's URL.
If still you are not getting it then let me know.

issue while loading image from image Path iOS Swift

well am trying this :
if let storedCoverImagePath = UC.coverImagePath{
let storedCoverImage = UIImage(contentsOfFile: storedCoverImagePath as String)
self.coverImage.image = storedCoverImage
self.backgroundImageView.image = storedCoverImage
}
and the value of storedCoverImagePath is :
/Users/remy/Library/Developer/CoreSimulator/Devices/D29D4F6F-E146-419D-B4B8-B1914F56569F/data/Containers/Data/Application/637675BB-EFA1-A8RT-8B73-A3628/DocumentsCoverImage.jpg
its straight forward that am trying to get an image from this storedCoverImagePath path. i double checked the path, image is there still am not able to set the image using this path, is there is something that am missing if yes than tell me please
You have to specify path relative to your apps bundle or directory. If you hardcode the path like you did:
/Users/remy/Library/Developer/CoreSimulator/Devices/D29D4F6F-E146-419D-B4B8-B1914F56569F/data/Containers/Data/Application/637675BB-EFA1-A8RT-8B73-A3628/DocumentsCoverImage.jpg
it gets ignored because of the sandboxing. iOS does not allow the app to reference directories external to the sandbox.
Possible solutions
One way to get it working is to add the image to the project. Then you can get it using:
let image : UIImage = UIImage(named:"ImageName")
Another way, if the image is saved in documents directory of your app, is to use:
let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let fileURL = documentsURL.URLByAppendingPathComponent(yourImageName)
let image = UIImage(contentsOfFile: fileURL.path!)

Get PHAsset from iOS Share Extension

I am developing a share extension for photos for my iOS app. Inside the extension, I am able to successfully retrieve the UIImage object from the NSItemProvider.
However, I would like to be able to share the image with my container app, without having to store the entire image data inside my shared user defaults. Is there a way to get the PHAsset of the image that the user has chosen in the share extension (if they have picked from their device)?
The documentation on the photos framework (https://developer.apple.com/library/ios/documentation/Photos/Reference/Photos_Framework/) has a line that says "This architecture makes it easy, safe, and efficient to work with the same assets from multiple threads or multiple apps and app extensions."
That line makes me think there is a way to share the same PHAsset between extension and container app, but I have yet to figure out any way to do that? Is there a way to do that?
This only works if the NSItemProvider gives you a URL with the format:
file:///var/mobile/Media/DCIM/100APPLE/IMG_0007.PNG
which is not always true for all your assets, but if it returns a URL as:
file:///var/mobile/Media/PhotoData/OutgoingTemp/2AB79E02-C977-4B4A-AFEE-60BC1641A67F.JPG
then PHAsset will never find your asset. Further more, the latter is a copy of your file, so if you happen to have a very large image/video, iOS will duplicate it in that OutgoingTemp directory. Nowhere in the documentation says when it's going to be deleted, hopefully soon enough.
I think this is a big gap Apple has left between Sharing Extensions and PHPhotoLibrary framework. Apple should've be creating an API to close it, and soon.
You can get PHAsset if image is shared from Photos app. The item provider will give you a URL that contains the image's filename, you use this to match PHAsset.
/// Assets that handle through handleImageItem:completionHandler:
private var handledAssets = [PHAsset]()
/// Key is the matched asset's original file name without suffix. E.g. IMG_193
private lazy var imageAssetDictionary: [String : PHAsset] = {
let options = PHFetchOptions()
options.includeHiddenAssets = true
let fetchResult = PHAsset.fetchAssetsWithOptions(options)
var assetDictionary = [String : PHAsset]()
for i in 0 ..< fetchResult.count {
let asset = fetchResult[i] as! PHAsset
let fileName = asset.valueForKey("filename") as! String
let fileNameWithoutSuffix = fileName.componentsSeparatedByString(".").first!
assetDictionary[fileNameWithoutSuffix] = asset
}
return assetDictionary
}()
...
provider.loadItemForTypeIdentifier(imageIdentifier, options: nil) { imageItem, _ in
if let image = imageItem as? UIImage {
// handle UIImage
} else if let data = imageItem as? NSData {
// handle NSData
} else if let url = imageItem as? NSURL {
// Prefix check: image is shared from Photos app
if let imageFilePath = imageURL.path where imageFilePath.hasPrefix("/var/mobile/Media/") {
for component in imageFilePath.componentsSeparatedByString("/") where component.containsString("IMG_") {
// photo: /var/mobile/Media/DCIM/101APPLE/IMG_1320.PNG
// edited photo: /var/mobile/Media/PhotoData/Mutations/DCIM/101APPLE/IMG_1309/Adjustments/FullSizeRender.jpg
// cut file's suffix if have, get file name like IMG_1309.
let fileName = component.componentsSeparatedByString(".").first!
if let asset = imageAssetDictionary[fileName] {
handledAssets.append(asset)
imageCreationDate = asset.creationDate
}
break
}
}
}

How to get directory of a folder inside xcode project? ios swift

I have bunch of tile images inside the folder called "Tiles"
I need to extract one image at a time from that folder, and set it to UIView object.
I am stuck on how to get the image from inside that folder.
Can anyone help do this in Swift?
If you have the image name,you can just access the image in this folder like this
let image = UIImage(named: "image.png")
Or this
let imageURL = NSBundle.mainBundle().URLForResource("image", withExtension: "png")
let image = UIImage(contentsOfFile: imageURL!.path!)
If you want get all images,you create a real folder inside the project
let imageArray = NSBundle.mainBundle().URLsForResourcesWithExtension("png", subdirectory: "Titles") as! [NSURL]
This will return an urlArray of png inside Titles folder.You can use contentsOfFile as show before to access image

Resources