I have link as below,
https://payood.test/loofpay/XUYZGlobal/WebForms/checkoutservice%20.aspx?paymentchannel=ddd&isysid=37268474138868&amount=25&description=Transaction From XXX&description2=dsdsd&tunnel=&original=ZXz4kfH9fiVIZ1jWBaGjww3hgwX84CGAahlCcsKWXvs%3d&responseUrl=http://localhost:55766/dsss/Response.aspx&hash=BE0481E5F9AA1C9F5B26A8E93A6ACAAD5888EDE9
When I try to open, its crashing saying below error.
fatal error: unexpectedly found nil while unwrapping an Optional value
Below is the code I am using
link = above link....
webView.loadRequest(URLRequest(url: URL(string: link)!))
Note:
If I use simple link as http://www.google.com, it works.
The link you've posted isn't a valid URL. It includes spaces in your description. You didn't encode this correctly.
As others mentioned, the problem is the link you provide to URL initializer is not a valid url and because of the !, your code can not initial a URL from the string in the following code and it will crash:
URL(string: link)!
So you have to change the string to some valid url before initializing a URL from it. Like this:
guard let escapedURLString = link.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) else {
fatalError("Unknown URL string:\(link)")
}
guard let finalURL = URL(string: escapedURLString) else {
fatalError("Can not create a url from:\(escapedURLString)")
}
print(finalURL) //to check if it works
webView.loadRequest(URLRequest(url: finalURL))
I found that url is already encoded but API have issues that they are sending spaces in url.
So I replace spaces with %20
link = link.replacingOccurrences(of: " ", with: "%20")
This way all is working fine now.
Related
In order to make HTTP request call using URLSession,I need to convert string to URL first so I have tried everything but just can’t convert this piece of string to URL(string: ).
This is the string:
“http://api-aws-eu-qa-1.abc-cde.com/v1/car-types/manufacturer?page=0&pageSize=10&wa_key=abc-cde-efg-44ccd99”
I can’t share the exact Url but format is all same.
The actual url with same format works fine in browser but no way in Swift, also that works fine in POSTMAN
I have also tried URLComponents which hepls me create the URL from components to URL but that fails with 400 status code response error.
I really appreciate the help, I am completely bogged down with this isuue and can’t proceed with my assignment.
Update: Tested with fiddler and request was not going through with this URL - "“http://api-aws-eu-qa-1.abc-cde.com%E2%80%8B/v1/car-types/manufacturer?page=0&pageSize=10&wa_key=abc-cde-efg-44ccd99”"
But when removed this %E2%80%8B in fiddler and resend it worked.
Any thoughts ..?
String to URL
let url = URL(string: "the url string goes here")
URL to String
let url = URL(string: "the url string goes here")
let urlString = url.absoluteString
Creating URL from URLComponents
var url: URL? {
var components = URLComponents()
components.scheme = "https"
components.host = "domain goes here" //example: twitter.com
components.path = "/path/goes/here"
components.queryItems = [
URLQueryItem(name: "item1", value: string1),
URLQueryItem(name: "item2", value: string2)
]
return components.url
}
try to add HEADER to you request:
let url = URL(string : urlString)
var request = URLRequest(url : url)
request.setValue("Application/json", forHTTPHeaderField : "Content-Type")
Your URL is:
http://api-aws-eu-qa-1.abc-cde.com%E2%80%8B/v1/car-types/manufacturer?page=0&pageSize=10&wa_key=abc-cde-efg-44ccd99`
The "host" portion is:
api-aws-eu-qa-1.abc-cde.com%E2%80%8B
%E2%80%8B encodes a ZERO WIDTH SPACE. This is a perfectly valid URL:
URL(string: "http://api-aws-eu-qa-1.abc-cde.com%E2%80%8B/v1/car-types/manufacturer?page=0&pageSize=10&wa_key=abc-cde-efg-44ccd99")
=> Optional(http://api-aws-eu-qa-1.abc-cde.com%E2%80%8B/v1/car-types/manufacturer?page=0&pageSize=10&wa_key=abc-cde-efg-44ccd99)
However, there is no such host as api-aws-eu-qa-1.abc-cde.com%E2%80%8B, so you should expect the actual connection to fail.
I expect that whatever is generating your URL strings has a bug.
If you are having trouble creating the URL itself (if URL(string:) return nil, then I expect this is not your actual URL string.
If you construct an URLComponents, the results are correct but may be slightly misleading:
URLComponents(string: "http://api-aws-eu-qa-1.abc-cde.com%E2%80%8B/v1/car-types/manufacturer?page=0&pageSize=10&wa_key=abc-cde-efg-44ccd99")?.host
Optional("api-aws-eu-qa-1.abc-cde.com")
While this looks like "api-aws-eu-qa-1.abc-cde.com", the string actually has a ZERO WIDTH SPACE at the end, which is invisible (but still part of the host field, which will correctly fail if you try to connect to it).
I am using firebase dynamic urls to shorten my url. I read the whole documentation and i dont understand why the code is not working.
here is my code:
let link = "https://mywebsite.com/share/?shop="+concatenate(getKey!,"&title="+shopName.text!.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!,"&desc="+summary.text!.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!,"&img="+profileImgURL)
linkBuilder.shorten() { link, warnings, error in // i get an error here sayiny "cannot find linkBuilder in scope"
guard let link = link, error != nil else { return }
print("The short URL is: \(link)")
}
what am i missing or doing wrong?
You forgot to define what linkBuilder is. Put this after let link =:
let dynamicLinksDomainURIPrefix = "https://example.com/link"
let linkBuilder = DynamicLinkComponents(link: link, domainURIPrefix: dynamicLinksDomainURIPRefix)
Documentation
Okay, so basically I'm creating a messenger app which I want to be able to upload and load a profile picture. Currently I can successfully upload a picture to firebase, but as stated in the title, it fails to download the picture URL.
(Tutorial that I am watching: https://www.youtube.com/watch?v=Hmr8PsG9E2w&list=PL5PR3UyfTWvdlk-Qi-dPtJmjTj-2YIMMf&index=18&ab_channel=iOSAcademy) 15-20 min into the video.
Where the error occurs:
strongSelf.storage.child("images/"+fileName).downloadURL(completion: {url, error in
guard let url = url else {
print("Failed to get download url")
completion(.failure(StorageErrors.failedToGetDownloadUrl))
return
}
let safeEmail = DatabaseManager.safeEmail(emailAddress: email)
let filename = safeEmail + "_profile_picture.png"
let path = "images/"+filename
Error message in console
What I've tried:
Changing and double checking that the path leads to the picture.
Trying different tactics of calling path like ("(path)") instead of (path)
Other random stuff that I found looking for this problem on the web
What my conclusion so far is that the program does not seem to indentify the correct path to the picture, but I've made sure that it looks identical to the video.
Would be awesome if anyone knows or has any idea how to deal with this issue? This is my first post so please tell me if more information is needed regarding the code is needed.
Cheers // Jakob
Adding extra to comments:
So the (error) is : failedToGetDownloadUrl
So this is where I suspect there is something going wrong:
strongSelf.storage.child("images/\(fileName)").downloadURL(completion: { url, error in
guard let url = url else {
print("Failed to get download url")
completion(.failure(StorageErrors.failedToGetDownloadUrl))
return
}
let urlString = url.absoluteString
print("download url returned: \(urlString)")
completion(.success(urlString))
})
})
}
And here are the Path to the images:
let safeEmail = DatabaseManager.safeEmail(emailAddress: email)
let filename = safeEmail + "_profile_picture.png"
let path = "images"+filename
And this is my firebase storage:
I am trying to open an Excel document that is located on a server. I wrote the following code but it always returns false for UIApplication.shared.canOpenURL(url as URL)
I think I am missing some requirement for deep linking to Excel. Why is iOS not able to understand ms-excel:ofe|u| format?
#objc static func openExcel() {
let originalString = "http://s000.tinyupload.com/download.php?file_id=23290165129849240725&t=2329016512984924072514118"
let encodedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
let encodedURLString = "ms-excel:ofe|u|" + encodedString! + "|n|TestDoc.xlsx|a|App"
if let url = NSURL(string: encodedURLString),
UIApplication.shared.canOpenURL(url as URL) {
UIApplication.shared.openURL(url as URL)
} else if let itunesUrl = NSURL(string: "https://itunes.apple.com/us/app/microsoft-excel/id586683407?mt=8&uo=4"), UIApplication.shared.canOpenURL(itunesUrl as URL) {
UIApplication.shared.openURL(itunesUrl as URL)
}
}
I have analyzed your code and found some mistakes. First, your URL was redirecting to somewhere, as per Microsoft documentation it can't handle redirecting URL's
The URL has to be encoded and must be a direct link to the file (not a
redirect). If the URL is in a format that Office cannot handle, or the
download simply fails, Office will not return the user to the invoking
application.
Here is Microsoft Documentation Link
The second mistake was you are only encoding the URL string containing site URL, you should consider the part after the scheme ms-excel: as a URL and should be encoded.
Because of improper encoding the let url = URL(string: encodedURLString) results nil that's why it is not working as expected.
Here is an example working code:
#objc static func openExcel() {
//replace the below url with yours. may be this one dosen't work
let originalString = "ofe|u|https://pgcconline.blackboard.com/webapps/dur-browserCheck-bb_bb60/samples/sample.xlsx"
let encodedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let encodedURLString = "ms-excel:" + encodedString!
if let url = URL(string: encodedURLString),
UIApplication.shared.canOpenURL(url) {
UIApplication.shared.openURL(url)
} else if let itunesUrl = NSURL(string: "https://itunes.apple.com/us/app/microsoft-excel/id586683407?mt=8&uo=4"), UIApplication.shared.canOpenURL(itunesUrl as URL) {
UIApplication.shared.openURL(itunesUrl as URL)
}
}
Note: From iOS 9 you must whitelist any URL schemes your App wants to query in Info.plist under the LSApplicationQueriesSchemes key (an array of strings):
For example in our case:
When i try to open the URL in the question above I get redirected to this URL, so my guess would be that your code is fine, it just might be that your excel file you're trying to open is really an HTML page since tinyupload apparently blocks direct links to the files.
Maybe try opening a direct excel file download link, https://pgcconline.blackboard.com/webapps/dur-browserCheck-bb_bb60/samples/sample.xlsx (it was the first google result for 'xlsx file sample download')
I'm using the OAuthSwift library to authenticate users of my app, but something doesn't seem to be working as it throws an error. After some debugging it seems to be going wrong on this line: parameters = url.query!.parametersFromQueryString()
It does have the url query string (set to url.query) but it somehow fails parsing the parametersFromQueryString(). Does someone else have this problem (with this library) and how did you solve it?
The "parametersFromQueryString" function can be found here: https://github.com/dongri/OAuthSwift/blob/1babc0f465144411c0dd9721271f239685ce83a9/OAuthSwift/String%2BOAuthSwift.swift
Create an extension of URL class and paste this code:
import Foundation
extension URL {
public var parametersFromQueryString : [String: String]? {
guard let components = URLComponents(url: self, resolvingAgainstBaseURL: true),
let queryItems = components.queryItems else { return nil }
return queryItems.reduce(into: [String: String]()) { (result, item) in
result[item.name] = item.value
}
}}
Now you can get the value of this calculated attribute from URL object by simply using:
url.parametersFromQueryString
Have you checked that url.query returns anything? and that it is url decoded before/after calling url.query?
try looking at the answers here:
URL decode in objective-c
If the method is looking for characters such as '?' or '=' and the URL is still encoded, it might not find them
Here is the same code as it should look like in swift:
let URLString = "http://sound17.mp3pk.com/indian/barfi/%5BSongs.PK%5D%20Barfi%20-%2001%20-%20Barfi!.mp3"
let URL = NSURL(string:url)
let filename = URL.path.lastPathComponent.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
//=> [Songs.PK] Barfi - 01 - Barfi!.mp3