I want to get Youtube Channel's picture. For getting Video picture it's so simple: http://img.youtube.com/vi/" + item.VideoId + "/mqdefault.jpg
Solved.
var json = new WebClient().DownloadString("http://gdata.youtube.com/feeds/api/users/"+YT_CHANNEL_NAME);
string str = "thumbnail url='";
string ImagePic = json.Substring(json.IndexOf("thumbnail url") + str.Length);
if (ImagePic.Contains("'"))
{
ImagePic = ImagePic.Remove(ImagePic.IndexOf("'"));
ImageChannel.ImageUrl = ImagePic;
}
Related
I want to open a url in web and automatically make a route between two points. I can't find correct url and params in google map document.
And for Swift 4 and swift 5
let apiKey = "https://www.google.com/maps/dir/" + userCurrentLocation.coordinate.latitude + "," + userCurrentLocation.coordinate.longitude + "/" + nextCurrentLocation.coordinate.latitude + "," + nextCurrentLocation.coordinate.longitude
var url = URL(string: apikey)
For objective c use
NSString *apikey = [NSString stringWithFormat:#"https://www.google.co.in/maps/dir/%f,%f/%f,%f",userCurrentLocation.coordinate.latitude,userCurrentLocation.coordinate.longitude,nextCurrentLocation.coordinate.latitude,nextCurrentLocation.coordinate.longitude;
NSURL *url = [NSURL URLWithString:apikey];
[[UIApplication sharedApplication] openURL:url];
You can do it like this in Swift 4 :
let url = URL(string: "https://maps.google.com")
if (UIApplication.shared.canOpenURL(url!))
{
let originLat:String = String(locationManager.location!.coordinate.latitude)
let originLong:String = String(locationManager.location!.coordinate.longitude)
let destLat:String = String(locationObj.latitude)
let destLong:String = String(locationObj.longitude)
let openUrlString:String = String(format:"https://www.google.com/maps/dir/?api=1&origin=%#,%#&destination=%#,%#&travelmode=driving",originLat,originLong,destLat,destLong)
print("openUrlString is : \(openUrlString)")
let openUrl = URL(string: openUrlString)
UIApplication.shared.open(openUrl!, options: [:]) { (res:Bool) in
}
}
I used to develop iOS Apps using Objective-C. Now I have recently migrated to Swift. In my app, I have a button that opens MS Outlook App with the pre-filled Subject and Body.
I did a similar App in Objective-C and used the below code to Encode my String for URL.
NSString *emailSubject = #"Test Subject";
NSString *encodedSubject = [emailSubject stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
Now I am unable to do the same in Swift 3. Below is the code that I tried.
var subjectText: String = "Test Subject"
var encodedSubject = subjectText.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
var stringURL: String = "ms-outlook://compose?subject=" + subjectText + "&body=TestingEmailNow"
// Convert the string to a URL.
var url = URL(string: stringURL)
// Open the app that responds to the URL scheme (should be Outlook).
UIApplication.shared.openURL(url!)
The error that I am getting is below.
fatal error: unexpectedly found nil while unwrapping an Optional value
2017-06-07 04:29:35.158030+0400 My App[1286:405793] fatal error: unexpectedly found nil while unwrapping an Optional value
I know that this error is coming due to the space in my Subject. I can say this because if I remove the space, I don't even have to encode it. It works directly. What am I doing wrong over here?
You made a simple mistake.
check your line
var stringURL: String = "ms-outlook://compose?subject=" + subjectText + "&body=TestingEmailNow"
you are using subjectText instead of encodedSubject
Complete code:
var subjectText: String = "Test Subject"
var encodedSubject = subjectText.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
if let encodedSubject = encodedSubject {
var stringURL: String = "ms-outlook://compose?subject=" + encodedSubject + "&body=TestingEmailNow"
// Convert the string to a URL.
var url = URL(string: stringURL)
if let url = url {
// Open the app that responds to the URL scheme (should be Outlook).
UIApplication.shared.openURL(url)
}
}
Variable used was the problem but I'd also suggest using URLComponents instead of building the URL as string.
var subjectText: String = "Test Subject"
var components = URLComponents()
components.scheme = "ms-outlook"
components.host = "compose"
components.queryItems = [
URLQueryItem(name: "subject", value: subjectText),
URLQueryItem(name: "body", value: "TestingEmailNow")
]
if let url = components.url {
UIApplication.shared.openURL(url)
}
I have a problem with backslash in strings.
When i create a string with this code:
let url = webProtocol + siteHost + "/tables/coupon?$expand=source&$filter=Source/Name eq '" + category + "'&" + siteApi
I expect this URL
https://swoup.azurewebsites.net/tables/coupon?$expand=source&$filter=Source/Name eq 'Recommended'&ZUMO-API-VERSION=2.0.0
But I get this
https://swoup.azurewebsites.net/tables/coupon?$expand=source&$filter=Source/Name eq \'Recommended\'&?ZUMO-API-VERSION=2.0.0
I tried to delete them using
stringByReplacingOccurrencesOfString("\\", withString: "")
But it doesn't help. Also I tried to add backslash before the ' but it doesn't help.
It's not clear based on your question, but I believe the backslashes are not actually in the string, but being printed by XCode. For example, enter the following into a playground:
let siteApi="test=123"
let category="Category1"
let webProtocol="https://"
let siteHost="www.testme.com"
let url = webProtocol + siteHost + "/tables/coupon?$expand=source&$filter=Source/Name eq '" + category + "'&" + siteApi
print( url)
And you will see the output does not contain backslashes.
https://www.testme.com/tables/coupon?$expand=source&$filter=Source/Name eq 'Category1'&test=123
Use NSURLComponents and NSURLQueryItem to build URLs, not string concatenation.
let components = NSURLComponents()
components.scheme = "https"
components.host = "swoup.azurewebsites.net"
components.path = "/tables/coupon"
let category = "Recommended"
let expand = NSURLQueryItem(name: "expand", value: "source")
let filter = NSURLQueryItem(name: "filter", value: "Source/Name eq '\(category)'")
let api = NSURLQueryItem(name:"ZUMO-API-VERSION", value:"2.0.0")
components.queryItems = [expand, filter, api]
Gives you this URL from components.URL:
https://swoup.azurewebsites.net/tables/coupon?expand=source&filter=Source/Name%20eq%20\'Recommended\'&ZUMO-API-VERSION=2.0.0
The error is in the variables that are not shown.
With this example complete (?) code example:
let webProtocol = "https://"
let siteHost = "swoup.azurewebsites.net"
let category = "Recommended"
let siteApi = "ZUMO-API-VERSION=2.0.0"
let url = webProtocol + siteHost + "/tables/coupon?$expand=source&$filter=Source/Name eq '" + category + "'&" + siteApi
print (url)
Output
https://swoup.azurewebsites.net/tables/coupon?$expand=source&$filter=Source/Name eq 'Recommended'&ZUMO-API-VERSION=2.0.0
There is no \.
How do you extract search keywords from Google search result page URL by Swift?
I was simply trying to get stings after "&q=" but I found out I needed to consider more complicated cases such as "https://www.google.co.jp/search?hl=ja&q=test#q=speedtest+%E4%BE%A1%E6%A0%BC&hl=ja&prmd=nsiv&tbs=qdr:d"
I would appreciate your advice.
Update:
As per advised by LEO, I put this way.
if let url = NSURL(string: urlStr){
var extractedQuery = ""
if let fragment = url.fragment {
extractedQuery = fragment
} else if let query = url.query{
extractedQuery = query
}
if let queryRange = extractedQuery.rangeOfString("&q="){
let queryStartIndex = queryRange.endIndex
let queryKeyword = extractedQuery.substringFromIndex(queryStartIndex)
print(queryKeyword)
}
}
You can convert your string to NSURL and access its query and fragment properties:
if let url = NSURL(string: "https://www.google.co.jp/search?hl=ja&q=test#q=speedtest+%E4%BE%A1%E6%A0%BC&hl=ja&prmd=nsiv&tbs=qdr:d"), query = url.query, fragment = url.fragment {
print(query) // "hl=ja&q=test\n"
print(fragment) // "q=speedtest+%E4%BE%A1%E6%A0%BC&hl=ja&prmd=nsiv&tbs=qdr:d\n"
}
I've been stuck on this for a while and cannot think logically how to resolve this, and would like some help.
Basically, I'm using the YouTube api to fetch all the video IDs from a changel. I store each of these IDs in an array, and I loop through its indices, each time calling this: https://developers.google.com/youtube/v3/docs/videos/list
This allows me to get the video duration of each video, where I put it in another array of AnyObjects and convert it to a recognizable format.
Here's the output of my videoIDs array, as I fetch it in groups of 10:
videoIDs = ["173ZNVycdQo", "NztC0z1JNq0", "U2C81DNHw2M", "09XKD2sS60E",
"Wc0cVjv44Xc", "ENKHANzmeh4", "mIW5trLZJcM", "KW0ehzTVo-s",
"1MyVzWIwFs4", "HyTQBpZeJCc"]
The problem is in the for loop as shown here:
for (var j = 0; j < self.videoIDs.count; j++)
{
self.getDurations("https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics,status&id=\(self.videoIDs[j])&key=\(self.apiKey)")
}
And Here's my getDurations function:
func getDurations(urlString: String)
{
let targetURL = NSURL(string: urlString)
performGetRequest(targetURL, completion: { (data, HTTPStatusCode, error) -> Void in
if HTTPStatusCode == 200 && error == nil
{
do
{
self.resultsVideoDurationsDict = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! Dictionary<NSObject, AnyObject>
print("resultsDict = \(self.resultsVideoDurationsDict)")
let items = self.resultsVideoDurationsDict["items"] as AnyObject!
// Loop through all items and add it to another dictionary
for (var i = 0; i < items.count; i++)
{
self.unformattedDurations.append(items[i])
}
}
catch
{
print(error)
}
}
else
{
print("HTTP Status Code = \(HTTPStatusCode)")
print("Error while loading channel details: \(error)")
}
})
}
At every iteration, the JSON of self.resultsVideoDurationsDict is different, i.e. the order of the video IDs within the videoIDs array does not correspond to the same order of data output from the JSON.
I know that due to time delays in the NSURLSession, some data may be fetched earlier than others.
Is there a way to remedy this to way to ensure my self.unformattedDurations contains the ordered data corresponding to the data in the videoIDs array?
Thanks.
UPDATE:
Here's one possible output of self.resultsVideoDurationsDict:
resultsDict = [etag: "DsOZ7qVJA4mxdTxZeNzis6uE6ck/EfACrkkmn5_QpCjD89FgcTdjxVY", kind: youtube#videoListResponse, items: (
{
contentDetails = {
caption = false;
definition = hd;
dimension = 2d;
duration = PT11M29S;
licensedContent = 0;
};
etag = "\"DsOZ7qVJA4mxdTxZeNzis6uE6ck/7wjJ90GVQP7Bo9GwdX8LfdJ8jdg\"";
id = HyTQBpZeJCc;
kind = "youtube#video";
snippet = {
categoryId = 22;
channelId = UC5ltMmeC4YFaart1SSXdmAg;
channelTitle = "Viet My Television";
description = "";
liveBroadcastContent = none;
localized = {
description = "";
title = "PSCD TIEC QUAN 4";
};
publishedAt = "2016-02-02T17:31:58.000Z";
thumbnails = {
default = {
height = 90;
url = "https://i.ytimg.com/vi/HyTQBpZeJCc/default.jpg";
width = 120;
};
high = {
height = 360;
url = "https://i.ytimg.com/vi/HyTQBpZeJCc/hqdefault.jpg";
width = 480;
};
maxres = {
height = 720;
url = "https://i.ytimg.com/vi/HyTQBpZeJCc/maxresdefault.jpg";
width = 1280;
};
medium = {
height = 180;
url = "https://i.ytimg.com/vi/HyTQBpZeJCc/mqdefault.jpg";
width = 320;
};
standard = {
height = 480;
url = "https://i.ytimg.com/vi/HyTQBpZeJCc/sddefault.jpg";
width = 640;
};
};
title = "PSCD TIEC QUAN 4";
};
statistics = {
commentCount = 0;
dislikeCount = 0;
favoriteCount = 0;
likeCount = 0;
viewCount = 14;
};
status = {
embeddable = 1;
license = youtube;
privacyStatus = public;
publicStatsViewable = 1;
uploadStatus = processed;
};
}
), pageInfo: {
resultsPerPage = 1;
totalResults = 1;
}]
The id of that result is HyTQBpZeJCc, which corresponds to the 9th index of the videoIDs array, not the first index. The first output should be for video ID 173ZNVycdQo. Therefore, different outputs are produced at runtime.