I need to use SoundCloud SDK into a Swift. Does someone have experience in this?
I have problem even at the start of their integration guide: https://developers.soundcloud.com/docs/api/ios-quickstart#authentication
When, in AppDelegate, I write
var scurl: NSURL
scUrl = NSURL(string: "www.francescocrema.it")!
SCSoundCloud.setClientID(idCode,secret: secCode, redirectURL: scUrl)
when it gets executed, the app crashed with SIGABRT and no visible error!
Plus, I can't manage to translate this code to Swift
- (IBAction) login:(id) sender
{
SCLoginViewControllerCompletionHandler handler = ^(NSError *error) {
if (SC_CANCELED(error)) {
NSLog(#"Canceled!");
} else if (error) {
NSLog(#"Error: %#", [error localizedDescription]);
} else {
NSLog(#"Done!");
}
};
[SCSoundCloud requestAccessWithPreparedAuthorizationURLHandler:^(NSURL *preparedURL) {
SCLoginViewController *loginViewController;
loginViewController = [SCLoginViewController
loginViewControllerWithPreparedURL:preparedURL
completionHandler:handler];
[self presentModalViewController:loginViewController animated:YES];
}];
}
Does someone know more about SoundCloud API?
Could you help me?
I am afraid SoundCloud API is not longer maintain by its team. I would recommend you to use your own library. I am using SoundCloud API as well so I decided to create one, maybe it can be useful for you.
ABMSoundCloudAPI on Github
Your redirectURL is invalid. SCRequest requires a URL with the scheme https:
NSAssert1([[aResource scheme] isEqualToString:#"https"], #"Resource '%#' is invalid because the scheme is not 'https'.", aResource);
Your Swift presentation code might look like this:
SCSoundCloud.requestAccess { (url) in
let loginViewController = SCLoginViewController(preparedURL: preparedUrl, completionHandler: nil)
self.present(loginViewController, animated: true)
}
Related
As Spotify framework is upgraded and new classes like SPTRemoteApp has
been introduced, I got totally frustrated to integrate it in old app
as they have changed almost every thing. So I need help if someone can
tell me these following points how it works. Somehow I feel I can do
login part but about track list and its playback part seems not
properly understandable from the Spotify developer docs for iOS.
How to get login Url from new Spotify framework or how to login by clicking button without checking login URL content.
How to get playlist like previously we get playlist by calling this method
[SPTRequest playlistsForUserInSession:session callback:^(NSError *error, SPTListPage *object) {
playListCount = [object.items count] - 1;
if (object.items) {
[object.items enumerateObjectsUsingBlock:^(SPTPartialPlaylist *obj, NSUInteger idx, BOOL *stop) {
[playlistURI addObject:obj.uri];
if (idx == object.items.count - 1) {
[weakSelf requestsTracks:playlistURI withSession:session];
}
spotifySynching = NO;
}];
}else{
spotifySynching = NO;
[self stopAnimatingTotalSpinner];
[self updateProgressDisplays];
}
}];
How to maintain and renew session, nd when we should renew it.
What is the replacement of these methods
(SPTListPage *)object;
[object requestNextPageWithSession:session callback:^(NSError *error, SPTListPage *object) {
[tracksURI addObjectsFromArray:object.items];
if ([object hasNextPage]) {
[self hasNextTrack:object withSession:session withNewObject:newObject];
}else{
[self requestsTracks:newObject withSession:session];
}
}];
[SPTRequest requestItemAtURI:obj withSession:session callback:^(NSError *error, SPTPlaylistSnapshot *object) {
if (error != nil) {
NSLog(#"*** Auth error: %#", error);
return;
}
[tracksURI addObjectsFromArray:object.firstTrackPage.items];
if ([object.firstTrackPage hasNextPage]) {
[self hasNextTrack:object.firstTrackPage withSession:session withNewObject:newObject];
}else{
[self requestsTracks:newObject withSession:session];
}
}];
Please check and let me know.
Thanks
Example project: http://cl.ly/360k3M3a2y05
I'm playing with the Reddit API for a school project, and came across this library for using it in Objective-C/Swift.
The professor wants us to get our toes wet with Swift, which I'm happy to do, and the goal of the project is to add an extra function onto an existing website's API. (I chose Reddit obviously.)
The mentioned library doesn't have a way to get all the subscriptions for a particular user (only to get one page at a time with the option to paginate), so I want to add the option to get them all in one clean call.
I'm leveraging the method in the aforementioned library that allows you to paginate, the method looks like this:
- (NSURLSessionDataTask *)subscribedSubredditsInCategory:(RKSubscribedSubredditCategory)category pagination:(RKPagination *)pagination completion:(RKListingCompletionBlock)completion {
NSMutableDictionary *taskParameters = [NSMutableDictionary dictionary];
[taskParameters addEntriesFromDictionary:[pagination dictionaryValue]];
NSString *path = [NSString stringWithFormat:#"subreddits/mine/%#.json", RKStringFromSubscribedSubredditCategory(category)];
return [self getPath:path parameters:taskParameters completion:^(NSHTTPURLResponse *response, id responseObject, NSError *error) {
if (!completion) return;
if (responseObject)
{
// A crude check to see if we have been redirected to the login page:
NSString *path = [[response URL] path];
NSRange range = [path rangeOfString:#"login"];
if (range.location != NSNotFound)
{
completion(nil, nil, [RKClient authenticationRequiredError]);
return;
}
// Parse the response:
NSArray *subredditsJSON = responseObject[#"data"][#"children"];
NSMutableArray *subredditObjects = [[NSMutableArray alloc] initWithCapacity:[subredditsJSON count]];
for (NSDictionary *subredditJSON in subredditsJSON)
{
NSError *mantleError = nil;
RKSubreddit *subreddit = [MTLJSONAdapter modelOfClass:[RKSubreddit class] fromJSONDictionary:subredditJSON error:&mantleError];
if (!mantleError)
{
[subredditObjects addObject:subreddit];
}
}
RKPagination *pagination = [RKPagination paginationFromListingResponse:responseObject];
completion([subredditObjects copy], pagination, nil);
}
else
{
completion(nil, nil, error);
}
}];
}
My addition is rather simple, I just call this above method recursively and save the pagination after each successful request, until there's no pages left, and then return the result:
- (void)allSubscribedSubredditsInCategory:(RKSubscribedSubredditCategory)category completion:(void (^)(NSArray *subreddits, NSError *error))completion {
RKPagination *pagination = [RKPagination paginationWithLimit:100];
[self recursiveSubscribedSubredditsWithPagination:pagination subredditsSoFar:[NSArray array] completion:completion];
}
- (void)recursiveSubscribedSubredditsWithPagination:(RKPagination *)pagination subredditsSoFar:(NSArray *)subredditsSoFar completion:(void (^)(NSArray *subreddits, NSError *error))completion {
[self subscribedSubredditsInCategory:RKSubscribedSubredditCategorySubscriber pagination:pagination completion:^(NSArray *newSubreddits, RKPagination *newPagination, NSError *newError) {
// If pagination is nil, we cannot go any further and have reached the end
if (newPagination == nil) {
NSArray *newSubredditsSoFar = [subredditsSoFar arrayByAddingObjectsFromArray:newSubreddits];
NSArray *subredditsWithoutDuplicates = [[NSSet setWithArray:newSubredditsSoFar] allObjects];
completion(subredditsWithoutDuplicates, newError);
} else {
NSArray *newSubredditsSoFar = [subredditsSoFar arrayByAddingObjectsFromArray:newSubreddits];
[self recursiveSubscribedSubredditsWithPagination:newPagination subredditsSoFar:newSubredditsSoFar completion:completion];
}
}];
}
So it looks like this in my viewDidLoad of my view controller:
RKClient.sharedClient().signInWithUsername("includedinproject", password: "includedinproject") { (error) -> Void in
RKClient.sharedClient().allSubscribedSubredditsInCategory(.Subscriber, completion: { (subreddits, error) -> Void in
print(subreddits)
}) <-- error occurs here?
}
However, whenever I call it, I get an EXC_BAD_ACCESS runtime error that doesn't really provide anything other than a memory address, and it appears to be caused at the end of the method in viewDidLoad, as labeled above.
The weird thing that occurs, however, is that this only occurs seemingly on the iPhone 4s simulator. If I build it to run on say, the newest 6s, it works fine. I'm puzzled (it has to work on all simulators for full points).
I went to my professor about it and he has no idea. We emulated the project in Objective-C (rebuilt the project as an Objective-C one) and the call seems to work fine.
My professor even did something with Instruments (not much experience myself) looking at "Zombies" and enabled it in the project as well, and nothing seemed to give him information either, we're both pretty confused.
What is going on here that's causing it to work great in Objective-C, and in Swift if the device isn't a 4s? Example project is at the top.
I have made a basic app using Twitter's fabric that allows user to tweet within my app and Provide Login With Twitter.Every things works a I Wanted.
How my app Works
If the user doesn't logged in to twitter my app allows him to login and if he is login then directly allows him to tweet.
Now the Big Part Comes
As I saw in many Apps I Can Remove my signed account from the app.And I am not able to get any method that help me to achieve this. I want to allow user to logout from twitter within my app whenever he/She wants.
I googled but i doesn't find anything
Here Is my Code:
- (IBAction)LogOut:(id)sender
{
[[Twitter sharedInstance]logOut];
}
- (IBAction)LogMeIn:(id)sender
{
[[Twitter sharedInstance] logInWithCompletion:^
(TWTRSession *session, NSError *error) {
if (session) {
NSLog(#"signed in as %#", [session userName]);
[LoginButton setTitle:#"LogOut" forState:normal];
} else {
NSLog(#"error: %#", [error localizedDescription]);
}
}];
}
this was a problem with NSCookie from Foundation framework And i slove this issues with help of below code
NSURL *url = [NSURL URLWithString:#"https://api.twitter.com"];
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url];
for (NSHTTPCookie *cookie in cookies)
{
[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
}
You need to use below code
[[[Twitter sharedInstance] sessionStore] logOutUserID:USERID];
Provide user id of the user you want to logout.
UPDATE: May 2016 - Framework has changed so this answer is no longer relevant.
See this answer:
https://stackoverflow.com/a/35765833/940709
and this answer:
https://stackoverflow.com/a/30916904/940709 instead.
[[[Twitter sharedInstance] sessionStore] logOutUserID:USERID];
This is the best simple answer for Swift 3:
let store = Twitter.sharedInstance().sessionStore
if let userID = store.session()?.userID {
store.logOutUserID(userID)
}
or you can use Naeem's answer but add () after store.session
Logout Code From Twitter Docs:
Objective-C
TWTRSessionStore *store = [[Twitter sharedInstance] sessionStore];
NSString *userID = store.session.userID;
[store logOutUserID:userID];
Swift
let store = Twitter.sharedInstance().sessionStore
if let userID = store.session()?.userID {
store.logOutUserID(userID)
}
For Swift try this,
/**
* Deletes the local Twitter user session from this app. This will not remove the system Twitter account nor make a network request to invalidate the session.
*
* #param userID ID of the user to log out
*/
Twitter.sharedInstance().sessionStore.logOutUserID(userId)
First make sure some user is signed in, then perform logout.
NSString *signedInUserID = [TWTRAPIClient clientWithCurrentUser].userID;
if (signedInUserID) {
[[Twitter sharedInstance].sessionStore logoutUserID:signedInUserID];
}
While login mention method as webBasedForceLogin, so that it will not create entry into Safari Cache.
private func twitterLogin() {
Twitter.sharedInstance().logIn(withMethods: .webBasedForceLogin, completion: { (session, error) in
if let error = error {
print(error.localizedDescription)
}
guard let session = session else {
return
}
print("success! Welcome \(session.userName).")
self.twitterButton.setTitle("TWITTER LOGOUT", for: .normal)
})
}
private func twitterLogout() {
let sessionStore = Twitter.sharedInstance().sessionStore
if let userID = sessionStore.session()?.userID {
sessionStore.logOutUserID(userID)
}
twitterButton.setTitle("TWITTER LOGIN", for: .normal)
}
Use below:
[TWTRSessionStore logout]
Deprecated:
[Twitter logOut]
is deprecated.
Users are encouraged to call - [TWTRSessionStore logout] instead of calling this method on the Twitter instance directly.
I'm having trouble with the authentication part of the SoundCloud API. I am following the tutorial located here: http://developer.soundcloud.com/docs/api/ios-quickstart#authentication
I follow their code as written and it runs/compiles, but doesn't authenticate. When requesting a login from the following bit of code:
(IBAction) login:(id) sender
{
SCLoginViewControllerCompletionHandler handler = ^(NSError *error) {
if (SC_CANCELED(error)) {
NSLog(#"Canceled!");
} else if (error) {
NSLog(#"Error: %#", [error localizedDescription]);
} else {
NSLog(#"Done!");
}
};
[SCSoundCloud requestAccessWithPreparedAuthorizationURLHandler:^(NSURL *preparedURL) {
SCLoginViewController *loginViewController;
loginViewController = [SCLoginViewController
loginViewControllerWithPreparedURL:preparedURL
completionHandler:handler];
[self presentModalViewController:loginViewController animated:YES];
}];
It returns with a console error of:
2013-12-26 16:11:23.902 SampleProject[14748:4717] -[NXOAuth2PostBodyStream open]
Stream has been reopened after close
2013-12-26 16:11:24.198 SampleProject[14748:70b] Done!
And then subsequent calls to [SCSoundCloud account] return nil.
During use of the app, the login views appear and I appear to have logged in successfully, but no account appears to have been saved / registered. Any advice?
Also, my initialization function with clientID / section / redirectURL are as directed in the tutorial and the app is registered.
Have a look at NXOAuth2Account.m where the user's client ID, client secret etc. are used to create the oauthClient.
You can also find in this file a method called description that should return everything you need to re-authenticate the user should you want to do so:
- (NSString *)description;
{
return [NSString stringWithFormat:#"<NXOAuth2Account identifier:'%#' accountType:'%#' accessToken:%# userData:%#>", self.identifier, self.accountType, self.accessToken, self.userData];
}
I'm using SCShareViewController from SoundCloud API in my project (iOS 7.0) so that the user can share your audio on SoundCloud AND on Facebook through the SoundCloud UI.
The upload in SoundCloud is working perfectly! But the share on facebook is not working =/
Does anyone can help me with this?
Is it necessary for me to create an app on facebook? Or does it already use SoundCloud's instead?
EDIT:
Here is my code:
NSURL *trackURL = [NSURL fileURLWithPath:trackPath];
SCShareViewController *shareViewController;
shareViewController = [SCShareViewController shareViewControllerWithFileURL:trackURL
completionHandler:^(NSDictionary *trackInfo, NSError *error){
if (SC_CANCELED(error)) {
NSLog(#"Canceled!");
} else if (error) {
NSLog(#"Ooops, something went wrong: %#", [error localizedDescription]);
} else {
NSLog(#"Uploaded track: %#", trackInfo);
}
}];
[self presentModalViewController:shareViewController animated:YES];