Hi I am really new to coding in Swift, and am trying to follow the codes in this book: http://www.apress.com/9781484202098. Learn iOS 8 App Development 2nd Edition by James Bucanek
In particular, I am working through Chapter 3 - building a URL shortening app, but despite having copied the code exactly, I am getting an error on the code in Page 76:
if let toShorten = webView.request.URL.absoluteString {
which states 'NSURLRequest?' does not have a member named 'URL'.
I have tried googling an answer, but unfortunately have not come across anything. Any response I can find seems to suggest that my code ought to be working (e.g. How to get url which I hit on UIWebView?). This seems to have the closest answer SWIFT: Why I can't get the current URL loaded in UIWebView? but the solution does not appear to work for me. If I add a ? after the request, it will then at least build it, but I then have a nil variable returned.
I am using Xcode v6.1.1. Here is the piece of code that is coming up with the error in ViewController.swift:
let GoDaddyAccountKey = "0123456789abcdef0123456789abcdef" //this is replaced by my actual account key in my own code
var shortenURLConnection: NSURLConnection?
var shortURLData: NSMutableData?
#IBAction func shortenURL( AnyObject ) {
if let toShorten = webView.request?.URL.absoluteString { // ? now added
let encodedURL = toShorten.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let urlString = "http://api.x.co/Squeeze.svc/text/\(GoDaddyAccountKey)?url=\(encodedURL)"
shortURLData = NSMutableData()
if let firstrequest = NSURL(string: urlString) //added if here and removed !
let request = NSURLRequest(URL:firstrequest)
shortenURLConnection = NSURLConnection(request:request, delegate:self)
shortenButton.enabled = false
}
}
}
If you have any suggestions on how I can fix this, I would really appreciate it!
Update:
Following suggestions from Ashley below, I have amended my code so that it is no longer bringing up the error (see comments above). However, it is now no longer running. This appears to be because the urlString is being created as http://api.x.co/Squeeze.svc/text/d558979bb9b84eddb76d8c8dd9740ce3?url=Optional("http://www.apple.com/"). The problem is therefore the Optional() that is included and thus makes it an invalid URL. Does anyone have a suggestion on how to remove this please?
request is an optional property on UIWebView:
var request: NSURLRequest? { get }
also stringByAddingPercentEscapesUsingEncoding returns an optional:
func stringByAddingPercentEscapesUsingEncoding(_ encoding: UInt) -> String?
What you need is to make user of optional binding in a few places:
if let toShorten = webView.request?.URL.absoluteString {
if let encodedURL = toShorten.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
let urlString = "http://api.x.co/Squeeze.svc/text/\(GoDaddyAccountKey)?url=\(encodedURL)"
shortURLData = NSMutableData()
if let firstrequest = NSURL(string: urlString) { // If a method can return a nil, don't force unwrap it
let request = NSURLRequest(URL:first request)
shortenURLConnection = NSURLConnection(request:request, delegate:self)
shortenButton.enabled = false
}
}
}
See Apple's docs on optional chaining for details
See Apple's docs for NSURL class
Related
In my Firebase database, I have a 'link' with some URL of a video as a value.
I'm trying to call it it via:
enum Media {
static let videoURL = "linkLabel.text = posts[selectedIndexPath].link"
}
Without success. If I call it just as a label text, it is fine. However, I also try the following:
static let videoURL = URL(string: "linkLabel.text = posts[selectedIndexPath].link")
As well as trying to call from my super.viewDidload() like:
videoVRView.load(from: URL(string: "\(linkLabel.text = posts[selectedIndexPath].link)"))
Anybody would know how to achieve this correctly? It will be amazing! Thanks!
----- EDIT:
I got it work by videoVRView.load(from: URL(string: "\(posts[selectedIndexPath].link)"))
Alright, I am not familiar with structs or the ordeal I am dealing with in Swift, but what I need to do is create an iMessage in my iMessage app extension with a sticker in it, meaning the image part of the iMessage is set to the sticker.
I have pored over Apple's docs and https://www.captechconsulting.com/blogs/ios-10-imessages-sdk-creating-an-imessages-extension but I do not understand how to do this or really how structs work. I read up on structs but that has not helped me accomplishing what Apple does in their sample code (downloadable at Apple)
What Apple does is they first compose a message, which I understood, taking their struct as a property, but I take sticker instead
guard let conversation = activeConversation else { fatalError("Expected a conversation") }
//Create a new message with the same session as any currently selected message.
let message = composeMessage(with: MSSticker, caption: "sup", session: conversation.selectedMessage?.session)
// Add the message to the conversation.
conversation.insert(message) { error in
if let error = error {
print(error)
}
}
They then do this (this is directly from sample code) to compose the message:
fileprivate func composeMessage(with iceCream: IceCream, caption: String, session: MSSession? = nil) -> MSMessage {
var components = URLComponents()
components.queryItems = iceCream.queryItems
let layout = MSMessageTemplateLayout()
layout.image = iceCream.renderSticker(opaque: true)
layout.caption = caption
let message = MSMessage(session: session ?? MSSession())
message.url = components.url!
message.layout = layout
return message
}
}
Basically this line is what Im having the problem with as I need to set my sticker as the image:
layout.image = iceCream.renderSticker(opaque: true)
Apple does a whole complicated function thing that I don't understand in renderSticker to pull the image part out of their stickers, and I have tried their way but I think this is better:
let img = UIImage(contentsOfURL: square.imageFileURL)
layout.image = ing
layout.image needs a UIImage, and I can get the imageFileURL from the sticker, I just cant get this into a UIImage. I get an error it does not match available overloads.
What can I do here? How can I insert the image from my sticker into a message? How can I get an image from its imageFileURL?
I'm not sure what exactly the question is, but I'll try to address as much as I can --
As rmaddy mentioned, if you want to create an image given a file location, simply use the UIImage constructor he specified.
As far as sending just a sticker (which you asked about in the comments on rmaddy's answer), you can insert just a sticker into an iMessage conversation. This functionality is available as part of an MSConversation. Here is a link to the documentation:
https://developer.apple.com/reference/messages/msconversation/1648187-insert
The active conversation can be accessed from your MSMessagesAppViewController.
There is no init(contentsOfURL:) initializer for UIImage. The closest one is init(contentsOfFile:).
To use that one with your file URL you can do:
let img = UIImage(contentsOfFile: square.imageFileURL.path)
So I'm trying to create a user on my database backend, everything is working on the app bar this segment on xcode, written in swift.
The backend can accept new users via this method but for some reason swift won't have it.
When I click register I get the error shown in the photo, code used
Alamofire.request(.POST, urlRequest, parameters: ["X-API-KEY": API_GENERAL_KEY,"username":userName.text!,"email": userMail.text!,"password":userPassword.text!,"profile_photo": self.imageName])
and the output is
<spotimusic.RadioStyleCollectionViewController: 0x7fe313d8fd00> whose view is not in the window hierarchy!
SDSD - Optional("nathan#trojan-audio.com")
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
Another error which shows in a segment is
Thanks for any help or suggestions
It seems that userName.text or userPassword.text doesn't have a value. This error can occur due to an unlinked outlet.
If your outlets are linked properly try this:
guard let userName = userName.text, let userMail = userMail.text, let userPassword = userPassword.text else {
return
}
Alamofire.request(.POST, urlRequest, parameters: ["X-API-KEY": API_GENERAL_KEY,"username":userName,"email": userMai,"password":userPassword,"profile_photo": self.imageName])
You will be able to catch the empty values without crashes.
Let me know if it fixes your problem
Thanks for all of the help guys, Marco's answer was the one that I used that fixed all the errors.
guard let userName = userName.text, let userMail = userMail.text, let userPassword = userPassword.text else {
return
}
Alamofire.request(.POST, urlRequest, parameters: ["X-API-KEY": API_GENERAL_KEY,"username":userName,"email": userMai,"password":userPassword,"profile_photo": self.imageName])
I'm getting this error in latest version of xcode using swift 2
on line
let s = linkTxt.text
Text in linkTxt appears by button "pasteFromClipBoard"
let s = linkTxt.text
let u = NSURL(string: s!)
let file = u?.lastPathComponent
What is the reason of it and how to fix it?
Update:
the problem appears in function saveData() which calls when file downloading is finished. It calls from NSURLSessionDataTask function. More interesting, that in start-downloading-button there are the same lines where filename is generating and there is no such error on it. I fixed these issues by declaring variables, writing text's values into them and use these variables in saveData() except textObject.text; I had to delete lines with NSUserDefaults from saveData() too because I got the same error. Did understand nothing >_<
Update 2:
It's really a bug. I've deleted this line and wrote again - problem fixed
linkTxt.txt is returning nil and NSURL(string: s!) will try to forcefully unwrap it.
let s = linkTxt.text
if let s = linkTxt.txt {
let u = NSURL(string: s!)
let file = u?.lastPathComponent
}
I am fairly new to swift programming language and I am trying to find a way to make a HTTP/API call from swift. I know how to do it exactly in Javascript because I have worked with it before quite a lot. But I can't seem to figure out in swift.
I found this code online and I have been testing this in XCODE Playground. But it is returning "nil"
The Code is below:
//: Playground - noun: a place where people can play
import UIKit
import XCPlayground // add this in
XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true)
var str = "Hello, playground"
// create a session object
let session = NSURLSession(
configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
// make a network request for a URL, in this case our endpoint
session.dataTaskWithURL(NSURL(string: "http://echo.jsontest.com/key/value/one/two")!,
completionHandler: { (taskData, taskResponse, taskError) -> Void in
// create an NSArray with the JSON response data
var jsonReadError:NSError?
let jsonArray = NSJSONSerialization.JSONObjectWithData(
taskData, options: nil, error: &jsonReadError) as! [AnyObject]
}).resume()
Can anyone tell me what am I doing wrong. Thank you.
If I have made a mistake please let me know or if you need further information please let me know.
Try this:
let jsonResult = NSJSONSerialization.JSONObjectWithData(taskData, options: NSJSONReadingOptions.MutableContainers, error: &jsonReadError) as! NSDictionary