Code Monkey home page Code Monkey logo

stravaswift's Introduction

StravaSwift

CI Status codebeat badge Version License Platform

This is a Swift wrapper for the Strava v3 API.

As this is a passion project, I only work on it when I have time. So, if you are interested in contributing, feel free to submit PRs.

Example

To run the example project, clone the repo, and run pod install from the Example directory first.

Installation

StravaSwift is available through the Swift Package Manager and CocoaPods.

Swift Package Manager

dependencies: [
    .package(url: "https://github.com/mpclarkson/StravaSwift.git", from: "1.0.1")
]

Cocoapods

To install it, simply add the following line to your Podfile:

pod "StravaSwift", '~> 1.0.1'

Quick Start

The full library documentation is available here.

  • First, you must register your app with Strava and get an OAuth client id and client secret.

  • Initialize the Strava Client as follows, preferably in your AppDelegate.swift to ensure it is configured before you call it:

let config = StravaConfig(
    clientId: YourStravaClientId,
    clientSecret: YourStravaClientSecret,
    redirectUri: YourRedirectUrl
)

StravaClient.sharedInstance.initWithConfig(config)
  • Note, by default the OAuth token is only available while the app is running, which means you need to request a new token. You can implement custom token storage and retrieval behaviour by overriding the default token delegate in the StravaConfig initializer which must implement the TokenDelegate protocol.

  • Register your redirect URL scheme in your info.plist file.

  • The authentication will use the Strava app be default if it is installed on the device. If the user does not have Strava installed, it will fallback on SFAuthenticationSession or ASWebAuthenticationSession depending on the iOS version. If your app is linked on or after iOS 9.0, you must add strava in you app’s info.plist file. It should be added as an entry fo the array under the LSApplicationQueriesSchemes key. Failure to do this will result in a crash when calling canOpenUrl:.

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>strava</string>
</array>
  • Implement the following method in your AppDelegate.swift to handle the OAuth redirection from Strava:
let strava = StravaClient.sharedInstance

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
    return strava.handleAuthorizationRedirect(url)
}
  • After authorizing, you can start requesting resources:
strava.authorize() { result in
    switch result {
        case .success(let token):
            //do something for success
        case .failure(let error):
            //do something for error
    }
}
  • Requesting resources:

The Router implementation is based on this Alamofire example:

strava.request(Router.athletes(id: 9999999999)) { (athlete: Athlete?) in
    //do something with the athlete
}

let params = [
    'page' = 2,
    'per_page' = 25
]

strava.request(Router.athleteActivities(params: params) { (activities: [Activity]?) in
   //do something with the activities
}

Todos

  • 100% API coverage (about 90% now)
  • Documentation
  • Tests
  • Better example app

Author

Matthew Clarkson, [email protected]

License

StravaSwift is available under the MIT license. See the LICENSE file for more info.

stravaswift's People

Contributors

agonzalezjr avatar dominicholmes avatar ehmjaysee avatar fleetphil avatar lludo avatar mpclarkson avatar tkikuchi2000 avatar ydemartino avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

stravaswift's Issues

Syntax for Upload .fit / .tcx file to strava

It seems like @DominicHolmes has added the code to enable upload functionality to StravaSwift.

It would be helpful to also include an example on how this upload can be achieved. I tried w/ my rudimentary understanding and am not able to figure out how to get it to work.

what is the correct syntax? Router.uploadFIle?

Appreciate if someone can help.

note: Latest TCX is basically this -->
file:///Users/testUser/Library/Developer/CoreSimulator/Devices/B4759D88-DFB6-43C0-A6E9-84FE3F23B9A0/data/Containers/Data/Application/BB9DAF96-51C5-4F16-BC42-C3EC1EBAA5F1/Documents/20201010-test.tcx

// StravaClient.sharedInstance.upload(Router.XXXX , upload: UploadData.init(activityType: "ride", name: "uploadName", description: "uploadDesc", private: true, trainer: true, externalId: "12345", dataType: "tcx", file: latestTCX)
// ,result: {UploadData.Status}
// ,failure: { (error: NSError) in
// debugPrint(error)
// })

authorize callback was not called in SwiftUI app

Hi there,
I have followed all the steps, added URI types, so I am able to open the Strava app, authorise and then redirect back to my app when calling StravaClient.sharedInstance.authorize { (result) in print(result) }
however the callback { (result) in print(result) } was not called.

It tried your example app, it worked! What am I still missing? I am writing my app using SwiftUI, that is the only difference I can spot.

Authorize callback problem

Hi

I am experiencing a problem when I try to authorize with the Strava app. I am able to open the Strava app, however the callback in StravaClient.sharedInstance.authorize was not called.

Everything works fine when I authorize with the browser.

Does anyone has a solution?

Thanks in advance

How to get the full details of athlete.

Not able to get list of bike , shoes and clubs
I have implement the StravaSwift but not getting details of athlete.

[id: Optional(2808157108)
resourceState: Optional(Dirtlej.ResourceState.summary)
externalId: nil
uploadId: nil
athlete: Optional(id: Optional(47192250)
resourceState: Optional(Dirtlej.ResourceState.meta)
firstname: nil
lastname: nil
profileMedium: nil
profile: nil
city: nil
state: nil
country: nil
sex: nil
friend: nil
follower: nil
premium: nil
createdAt: nil
updatedAt: nil
friendCount: nil
followerCount: nil
mutualFriendCount: nil
datePreference: nil
measurementPreference: nil
email: nil
FTP: nil
weight: nil
clubs: Optional([])
bikes: Optional([])
shoes: Optional([])
)

No error response from request if network unavailable

I ran a data request with airplane mode set on the target iPhone expecting an error response from the Strava Client, however I don't seem to get any response from the Alamofire request - the debug output shows the expected error but as far as I can see this message is coming from the Foundation library, not StravaSwift or Alamofire:

2019-10-23 18:31:24.637011+0100 RideViewer2[6907:2217779] Task <31B1E946-16F8-4DB1-8B7E-773E6D2DD9A4>.<1> finished with error [-1009] Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo={_kCFStreamErrorCodeKey=50, NSUnderlyingError=0x28093a7f0 {Error Domain=kCFErrorDomainCFNetwork Code=-1009 "(null)" UserInfo={_kCFStreamErrorCodeKey=50, _kCFStreamErrorDomainKey=1}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <31B1E946-16F8-4DB1-8B7E-773E6D2DD9A4>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <31B1E946-16F8-4DB1-8B7E-773E6D2DD9A4>.<1>"
), NSLocalizedDescription=The Internet connection appears to be offline., NSErrorFailingURLStringKey=https://www.strava.com/api/v3/athlete/activities?after=1571147109&page=1&per_page=100, NSErrorFailingURLKey=https://www.strava.com/api/v3/athlete/activities?after=1571147109&page=1&per_page=100, _kCFStreamErrorDomainKey=1}

I suspect that this issue is related to the one in this thread - https://github.com/Alamofire/Alamofire/issues/2311 - but my expertise is not good enough to confirm this or work out a fix...

Any thoughts?

Support for Alamofire 4.0

I have this error:

[!] Unable to satisfy the following requirements:

  • Alamofire (~> 3.1) required by StravaSwift (0.1.0)

WatchOS Support

Is there anything preventing WatchOS support at this point? Is it just a matter of updating the podspec?

How to get bike list in the Athlete

We are not getting the athlete details like this,

[id: Optional(2808157108)
resourceState: Optional(Dirtlej.ResourceState.summary)
externalId: nil
uploadId: nil
athlete: Optional(id: Optional(47192250)
resourceState: Optional(Dirtlej.ResourceState.meta)
firstname: nil
lastname: nil
profileMedium: nil
profile: nil
city: nil
state: nil
country: nil
sex: nil
friend: nil
follower: nil
premium: nil
createdAt: nil
updatedAt: nil
friendCount: nil
followerCount: nil
mutualFriendCount: nil
datePreference: nil
measurementPreference: nil
email: nil
FTP: nil
weight: nil
clubs: Optional([])
bikes: Optional([])
shoes: Optional([])
)

ASWeb Auth error due to redirector encoding issue

Here is a workaround solution https://stackoverflow.com/a/65092728/14414215 but this also causes issue as there are 2 diff methods of handling the redirectUri depending on if user has the strava app installed on the phone or otherwise.

The percent encoding example (SO link above) is needed if the user does not have the strava app install on the phone. Hence, StravaSwift will fallback to using ASWebAuth.

However, when using this percentEncoding solution, this would then break the authentication callback when the user has the Strava App in the phone. This would then return as "FALSE" once user has fully authenticated in the strava app and returned back to the originating app. (this then breaks the app)

My solution was to do something dumb to this line.

if let redirectUri = config?.redirectUri, url.absoluteString.starts(with: redirectUri),

Basically, replacing the occurrence of the PercentEncoding back to "://" else the comparison (url.absoluteString.starts(with: redirectUri),) fails.

   if let redirectUri = config?.redirectUri.components(separatedBy: "%3A%2F%2F").joined(separator: "://"), url.absoluteString.starts(with: redirectUri),

Gear ID Router is Int but requires String

When making a call to the Strava API via Alamofire, the Router parameter only accepts Int values for the gear.id
However, the gear defined in the Strava API documentation is listed as a String.

Thoughts?

Problems with auth

Hello! I have an issue with stava authorization. And it seems to me that the problem is in Network layer -> Alamofire.
Inside
oauthRequest(Router.token(code: code))?.responseStrava
I always receive 401 Unauthorized

But when I use a simple base URLSession request with the same params, like in your Router, everything is OK and auth succeeds.

I can provide more information if needed.

Can you check please on your side and confirm that auth fails?

Thanks.

Class Effort has incorrect return type for Activity

Class Effort is written expecting that Strava returns an Activity property in a DetailedSegmentEffort response. In fact the activity returned is an instance of MetaActivity that contains only an activity ID. This error means that the result returned in StravaSwift by an Effort class does not contain a reference to a valid activity
What is required is to add a class for MetaActivity with the correct data

Can't end BackgroundTask

Hi,

When I execute the code "Strava.authorize" in a iOS 13 iPhone, the log launch the following error:

Can't end BackgroundTask: no background task exists with identifier 2 (0x2), or it may have already been ended. Break in UIApplicationEndBackgroundTaskError() to debug.

That error makes the app doesn't retrieve the auth token from Strava api. However, if I execute the app in the iOS Simulator, it works fine.

Is there some extra configuration that It has to be set?

How to use ActivitiesZones?

Looking to use the ActivitiesZones that is in the Router.swift file. How would I go about using it to request/get time spent in different zones (power, heart rate, pace). Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.